Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always removeEventListener?

Say I add a load event to the window like so:

window.addEventListener("load",initialize);

Should I then remove the load event listener from the window after the event is fired? It only fires once, but will it continue to listen after that happens?

It's simple enough to do:

function initialize(event_){
    /* Just by adding this line. */
    window.removeEventListener("load",initialize);
}

But is that overkill or will that actually benefit the performance of my program? I only ask because the "load" event only fires once, so it would make sense if it just resolved itself. I've never heard of a self resolving listener, though... Any thoughts?

Edit: Also, I'm not concerned specifically with the "load" event, just the general scenario where the listener continues to listen for an event that only fires once.

like image 710
Frank Avatar asked Apr 05 '15 15:04

Frank


People also ask

Do we need removeEventListener?

Typically it's overkill, as this doesn't make a huge difference. Of course, it might trigger garbage collection on initialize , which could save a bit of memory (or more, depending on your code structure) and improve performance by making it available to the rest of your app.

Why do you need removeEventListener?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

What happens if you dont remove event listener?

The main reason you should remove event listeners before destroying the component which added them is because once your component is gone, the function that should be executed when the event happens is gone as well (in most cases) so, if the element you bound the listener to outlasts the component, when the event ...

Is it important to remove event listener in JavaScript?

Removing the event listener using JavaScript Removing the event listener from a specific HTML element can be so important in some cases as you don't want the event to get triggered multiple times without any reason.


1 Answers

window.addEventListener('load', initialize, {once: true});

like image 107
daGo Avatar answered Sep 30 '22 14:09

daGo