sveltejs / svelte-scroller

A <Scroller> component for Svelte apps
https://svelte.dev/repl/76846b7ae27b3a21becb64ffd6e9d4a6
Other
347 stars 25 forks source link

Only update index if a new section is 'selected' #14

Closed jtrim-ons closed 3 years ago

jtrim-ons commented 3 years ago

Currently, index is updated on every scroll event, even if its value has not changed. This makes it tricky to add a function that is run only when a new section comes into view (which is probably what is required in #11, for example).

To see the current behavior, add the following line to the end of the script block in App.svelte in the demo.

    $: console.log('Current section: ' + index);

As you scroll, 'Current section: 0' is logged many times.

The new version in this pull request only updates index (and calls any corresponding functions) if a new section is scrolled into position. This is done by using a new variable i rather than index as the index variable for the for-loop. Thus, index is only changed when the current section has changed.

Rich-Harris commented 3 years ago

thank you!