Does element.parentNode.removeChild (element) require element.removeEventListener ()?

Let's say I have an array of elements in my document that are children of the same object. Each of these elements registers a new event listener with a different parameter. If I drop the parent, do I need to manually uninstall all eventListeners? Or does the browser keep track of all event listeners and discard them when I remove elements from the DOM? The reason I am asking is because it is very difficult to track all events and then call removeEventListeners. It seems like the browser must be smart enough to figure this out, but I'm afraid I'm 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 understand that an easy way would be to store a reference to the event listener on the element itself, but I'm wondering if changing the element's type might cause additional performance issues?

+3


source to share


1 answer


In modern browsers, you don't 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 (for example, a reference to a DOM element stored in a JS variable), then the DOM element will be garbage collected after deletion.



The DOM GC is smart enough to know that an event listener is not considered a reference to that DOM element after it has been removed from the DOM (since DOM events cannot occur when they are removed from the DOM).

+4


source







All Articles