Say I have a container with various elements inside. In turn, any element could have various event listeners.
<div id="container">
<video src="movie.mp4"></video>
<a>Some button</a>
</div>
With Prototype JS, how do you properly remove each element and their event listeners from memory? The following is the explicit way to clean everything:
$('container').childElements().each(
function(child) {
Event.stopObserving(child);
child.remove();
}
);
The following is a much quicker way to clear the container:
$('container').update();
But will it cause memory leaks? Will most javascript engines understand that if I clear the innerHTML, I also want to clear the event listeners on each element?
Generally, event handlers will go away when the element goes away. Clearing the
innerHTMLof the container destroys all contained elements, thus the attached event handlers.Older versions of Internet Explorer (<= IE8) have problems re-claiming memory from event handlers when the owning element was destroyed. To accommodate them, you should use
Event.stopObserving.To be absolutely sure, you could extend
Elementlike this:This removes all events from all descendants before re-setting the element contents itself. It does not seem like
Event.stopObserving()itself is recusive, so without that step there might still be leaks from elements “further down”. Use it like this:See this as a jsFiddle.
Disclaimer: I am not familiar with prototype. If the above is incorrect, please leave a comment.
Related reading: