Quick Tip: Managing event listeners with bound callbacks

Always remove your event listeners

It’s important to remember to remove event listeners after you’re done using them. This is good for performance and allows code to be garbage collected and removed from memory when no longer needed.

The problem

Consider some code like

thing.addEventListener(‘click’, this.func.bind(this))

Unfortunately, you cannot remove the event listener in the same manor. I.E:

thing.removeEventListener(‘click’, this.func.bind(this))

Won’t work at all. ** sad trombbone **

Why doesn’t this work?

This doesn’t work because every time bind is used, a new function is created!
This means that when it’s time to call removeEventListener, the callback function no longer matches the original that was used in addEventListener (anonymous functions will behave this way too).

The fix

const func = doStuff.bind(this);
thing.addEventListener(func);

/** later on **/

thing.removeEventListener(func);

Link: https://dev.to//tevko/quick-tip-managing-event-listeners-with-bound-callbacks-ji9