loading...
Cover image for Quick Tip: Managing event listeners with bound callbacks

Quick Tip: Managing event listeners with bound callbacks

tevko profile image Tim Evko ・1 min read

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);

Discussion

pic
Editor guide
Collapse
qm3ster profile image
Mihail Malo

In practical use, when would you be removing event listeners?
I feel like when you recycle elements, like an infinite list, event delegation should be used instead to prevent closure allocations.
And in the normal case, you just drop the element and its listeners get garbage collected with it.
There's probably a time to use this, but it's slipping my mind at the moment. Maybe something with scroll/draggables?
Also non-UI EventEmitters of course.

Also, manor should probably be manner

Collapse
abrahamtourdex profile image
Abraham Brookes

I assign my event listeners to the document, and check against the event.target to see what should happen when the event is triggered. I figure this eliminates a slew of event listeners and is good for optimization. I don't think the benefits of removing event handlers would really be worth it in my case, what do you think? Are you more referring to a situation in which you have lots of dynamically added elements? I would still lean towards capturing their events on the document, I think.

Collapse
ethansteininger profile image
Ethan

I feel like most event listeners are always relevant on the page. Can you think of any scenarios when this isnt the case?