首页 > 解决方案 > removeEventListener not working on custom directive

问题描述

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?

标签: javascriptvue.jsvue-directives

解决方案


推荐阅读