Quick Tip: Managing event listeners with bound callbacks
Tim
Posted on February 26, 2019
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 manner. 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);
Posted on February 26, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.