Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is element.removeEventListener() required before element.parentNode.removeChild(element)?

Let's say I have an array of elements in my document which are children of a single object. Each of these elements registers a new event listener with a parameter that's different. If I discard the parent object, do I need to manually de-register all eventListeners? Or is the browser keeping track of all event listeners and discards them when I remove the elements from the DOM? The reason I ask is because it's pretty painful to keep track of all events, and then call removeEventListeners. It seems that the browser should be smart enough to figure out this, but I am afraid I am going to leak memory if I don't.

As an example:

var elements = parent.childNodes;
var listeners = [];
for (var i = 0; i<elements.length; i++) {
   listeners.push(elements[i].addEventListener('click',function() { alert(i); }));
}

and later:

for (var i = 0; i<elements.length; i++) {
   elements[i].removeEventListener(listeners[i]);  // is this really required?
}
parent.parentNode.removeChild(parent);

What's the typical approach? I realize a simple way would be to store the event listener reference on the element itself, but I wonder if modifying the type of the element is going to cause extra performance issues?

like image 345
edeboursetty Avatar asked Oct 18 '14 16:10

edeboursetty


1 Answers

In modern browsers, you do not need to remove event listeners before removing elements from the DOM. If there are no direct references to that particular DOM element elsewhere in your javascript (e.g. the DOM element reference stored in a JS variable), then the DOM element will be garbage collected after removal.

The DOM GC is smart enough to know that an event listener does not count as a reference to that DOM element once it's been removed from the DOM (because DOM events cannot happen when it is removed from the DOM).

like image 67
jfriend00 Avatar answered Nov 15 '22 23:11

jfriend00