motiondivision / motionone

https://motion.dev
MIT License
2.84k stars 52 forks source link

[Feature] Destroy/Stop Scroll-Events (on Vue unmounted-hook) #197

Open 54mu3l opened 1 year ago

54mu3l commented 1 year ago

How I use motion

I'm using scroll to track scroll events. Based on the progress I receive from motion some texts and graphics are changed.


The problem

I'm using Vue.js and I run the following code in the mounted-hook:

const scrollOptions = {
  target: target,
  container: scrollContainer,
  offset: ['end end', 'start 100px'],
};
scroll(({ y }) => {
  animateText(y.progress);
}, scrollOptions);

Which means every time the component is mounted, a new scroll event is registered and I end up with multiple events active at the same time. And I don't see any solution to unsubscribe/stop the scroll event.


The solution

I'd like to stop the scroll event listener in the Vue unmounted-hook. (See Vue Lifecylce for reference: https://vuejs.org/guide/essentials/lifecycle.html#lifecycle-diagram)

I'd imagine scroll could return an id which could be used to stop the event. Similar to setInterval (https://developer.mozilla.org/en-US/docs/Web/API/setInterval)

function changeColor() {
  nIntervId = setInterval(flashText, 1000);
}

function stopTextColor() {
  clearInterval(nIntervId);
  // release our intervalID from the variable
  nIntervId = null;
}

Or even better: scroll could return an object which contains a stop function.

onMounted(() => {
  const scrollOptions = {
    target: target,
    container: scrollContainer,
    offset: ['end end', 'start 100px'],
  };
  myScrollEvent = scroll(({ y }) => {
    animateText(y.progress);
  }, scrollOptions);
})

onUnmounted(() => {
  myScrollEvent.stop()
})

This might me related to https://github.com/motiondivision/motionone/issues/141

mathg commented 9 months ago

Any update on this feature? We encounter the same issue on Sveltekit. When navigating to another page, the scroll watcher is still present and it creates errors. A method like ScrollTrigger's destroy() should exist to solve this type of problem.