0

So i have a directive it will run a function after it reached a certain threshold from the top of the viewport but i cannot seem to remove the event listener :/.

Here is the directive:


    const scrollHandler = (el, binding) => {
      const yOffset = el.getBoundingClientRect().y;
      const isScrolled = document.body.scrollTop > (yOffset - 20) || document.documentElement.scrollTop > (yOffset - 20);
      binding.value(isScrolled, el);
    };
    
    const GlobalDirectives = {
      install(Vue) {
        Vue.directive('scroll-watch', {
          inserted(el, binding) {
            window.addEventListener('scroll', () => scrollHandler(el, binding));
          },
          unbind(el, binding) {
            window.removeEventListener('scroll', () => scrollHandler(el, binding), true);
            console.log('is unbind');
          },
        });
      },
    };

and in the component:

<template>
  <section v-scroll-watch="doSomething">
    // html
  </section>
</template>

<script>
export default {
  methods: {
    doSomething(val, el) {
      console.log(val, el);
    },
  },
};
</script>

even when i navigate to another route somehow i can see that unbind is working but it still calls the event listener. can anyone tell me what im doing wrong?

dunhilblack
  • 195
  • 1
  • 4
  • 13
  • `.removeEventHandler()` expects the exact same function you've used for `.addEventListener()` hence you cannot use an anonymous function (unless you store it in a variable). Give the function a name and use that. – Andreas Dec 07 '20 at 10:45
  • [How to remove an event listener in javascript?](https://stackoverflow.com/questions/15100576/how-to-remove-an-event-listener-in-javascript) – Andreas Dec 07 '20 at 10:49
  • `() => scrollHandler(el, binding)` is not the same as `() => scrollHandler(el, binding)` .... just like `{} !== {}` – Bravo Dec 07 '20 at 11:09

0 Answers0