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 eventListener
s? 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 removeEventListener
s. 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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With