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

Posted on by:

tevko profile

Tim Evko

@tevko

Christ follower. Husband. Crossfitter. Software Developer. Here to help you with your career in tech. patreon.com/Devcareeradvice Text me at (617) 993-6431. πŸ‡ΊπŸ‡Έ

Discussion

markdown guide
 

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

 

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.

 

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