Skip to content
Advertisement

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

Code :-

JavaScript

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():

JavaScript

demo

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