0

Problem
When I add a new native event listener (el.addEventListener('scroll', () => blabla)) on component mounting, should I remove it on component destroy? Or it will get removed automatically?

All the examples I find online are referred to window.addEventListener, which, as expected, do not get deleted at any time during the lifetime of the app and therefore require a manual listener cleanings.

My Code
I created a custom Vue directive to detect component scrolling event, and attached a listener on the insert hook, and wonder if I should also remove the listener on unbind hook.

My directive code:

  bind(el, binding) {
    el._scrollHandler = evt => binding.value(evt, el);
    el.addEventListener('scroll', el._scrollHandler);
  },

  unbind(el) {
    el.removeEventListener('scroll', el._scrollHandler);
  }
Shay Yzhakov
  • 975
  • 2
  • 13
  • 31
  • will the listener affect your application in any way even after the component is deleted? – yqlim Dec 12 '18 at 01:53
  • How can i now that? The listener is a scroll listener that listens to scrolling inside that component, but when the component is gone I cannot test it anymore. I just wanna make sure the listener wouldn't just "stay" there as a garbage.. – Shay Yzhakov Dec 13 '18 at 06:20
  • 1
    take a look at [this](https://stackoverflow.com/questions/8547363/does-javascript-remove-event-handlers-of-deleted-dom-elements) and [this](https://stackoverflow.com/questions/6033821/do-i-need-to-remove-event-listeners-before-removing-elements#answer-37096563). – yqlim Dec 13 '18 at 06:38

0 Answers0