Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Listener Remove or Keep - Best Practice

I have quite a few jquery / javascript listeners on my web page and I will reduce them as much as I can. However, for the listeners that remain, there are scenarios where I make them display:none at certain points. Here are my questions:

1) What is best practice regarding listeners, should I add or remove listeners as I show / hide elements?

2) Which is best performance wise?

3) If I end up having lots of listeners, is it best to apply an on listener event to the whole body, or is it best to apply listeners to only things that need listening to?

like image 697
Wickey312 Avatar asked Apr 17 '15 20:04

Wickey312


People also ask

Is it necessary to remove event listener?

Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.

Should I remove event listeners react?

Always cleanup your event listeners. Do this with window. removeEventListener when your component unmounts. By cleaning up, you'll avoid listening to events multiple times and memory leaks.

Are event listeners removed when element is removed?

According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use . detach() instead.

Can event handlers be removed?

Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.


1 Answers

A general rule of thumb is as follows:

Remove events on teardown.

Since you are not removing the DOM element, the listener should persist, performance wise there is no drawback unless you have hundreds of thousands of listeners.

The time it takes to micromanage hidden elements listeners aren't enough to outweigh any perceived performance gains.


  1. Remove listeners when you remove elements (teardown).
  2. Listen to a generic class applied to multiple elements instead of individual elements, use data attributes to identify them if required.
  3. Listen to things that need to be listened to.

You can also use event delegation (bubbling) for when you have a large number of children that require listening to by listening on the parent:

$('div').on('click', function (e) {
  // check e.target for specific child node you require listening on
})
like image 115
Nijikokun Avatar answered Sep 18 '22 23:09

Nijikokun