Skip to content
Advertisement

How to remove an eventListener (window.removeEventListener) in Vue 2, when certain condition is met

Code :-

<template>
// html
</template>

<script>
import _ from "lodash";

 data() {
    return {
      renderComponent: false,
    };
  },
 watch: {
// when this property is true, want to stop calling scroll event with this.onScroll method
    renderComponent(val) {
      if(val === true) {
        console.log("////////I am removing you");
        window.removeEventListener('scroll', this.onScroll);
      }
    }
  },
 methods: {
    onScroll() {
      console.log("I am called////////");
      let similarTickerHeading = this.$refs.similarTicker;
      if(similarTickerHeading) {
       let margin = similarTickerHeading.getBoundingClientRect().top;
       let innerHeigth = window.innerHeight;
        console.log("Window Screen", innerHeigth);
        console.log("Component located", margin);
       
// when this condition is true, I want to stop listening for the scroll event with this (onScroll method)
       if(margin - innerHeigth < 850) {
          console.log("I should start loading the actual component");
          this.renderComponent = true;
          this.$vs.loading.close("#loader-example > .con-vs-loading");
          // removing eventListener for scrolling with the onScroll Method
          window.removeEventListener('scroll', this.onScroll);
       }
      }
    }
  },
  mounted() {
    this.renderComponent = false;
     this.$vs.loading({
        container: "#loader-example",
        type: "point",
        scale: 0.8,
      });

    this.$nextTick(function() {
      window.addEventListener('scroll', _.throttle(this.onScroll,250));
      this.onScroll();
    })
  },
 beforeDestroy() {
    window.removeEventListener('scroll', this.onScroll);
  },
</script>

In the above code, I want to stop listening for the scroll event with onScroll method when my if block in onScroll method becomes true. But, still, the onScroll method gets called whenever I scroll even though when I tried to remove the eventListener. I even created a watcher to remove the eventListener, yet the method keeps on getting called on scroll.

How can I remove the scroll eventListener with onScroll method ?

UPDATE : If I remove throttling and cut out _.throttle, the scroll event does get removed. Due to the use of _.throttle, I cannot remove the scroll event listener.

Advertisement

Answer

The function reference passed to window.addEventListener() must be the same reference passed to window.removeEventListener(). In your case, there are two different references because you’ve wrapped one of them with _.throttle().

Solution

Cache the function reference passed to addEventListener() so that it could be used later for removeEventListener():

export default {
  mounted() {
              👇
    this._scrollHandler = _.throttle(this.onScroll, 250)

    this.$nextTick(() => {                        👇
      window.addEventListener('scroll', this._scrollHandler);
      this.onScroll();
    })
  },
  beforeDestroy() {
                                                    👇
    window.removeEventListener('scroll', this._scrollHandler);
  },
}

demo

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement