Let’s say I have a page that loads pages dynamically. As each page loads into the DOM, events for the elements in that page are added.
If the user loads another page, the elements loaded previously will be removed from the DOM. Naturally, because the elements themselves no longer exist, any events mapped to those elements cease to function.
However, are they also removed? Or are they sitting in the user’s memory, taking up space?
Follow-up:
Were a function defined as such:
var event = $('foobar').addEvent('click', function() {
alert(1);
});
One could easily remove the event with event = null (or so I’d assume!)…
but what if the event were not saved to a local variable?
$('foobar').addEvent('click', function() {
alert(1);
});
Thanks!
first of all. what? this makes no sense:
it does not save the event into a local variable as you seem to think. it saves a reference to the
foobar element objectinto theeventvariable – most mootools element methods will returnthisfor chaining, which is the element itself and not the result of the method (unless it’s a getter like ‘.getStyle’).it then depends on how you get rid of the element what happens next. first off,
element.destroy, found here: https://github.com/mootools/mootools-core/blob/master/Source/Element/Element.js#L728it will remove the element from the dom and from memory, and empty it in a safe way. it will be reliant on the browser’s GC to clean up once it’s gone, mootools won’t do any spectacular GC for you for the element itself but it does run the special
cleanfunction on the child nodes as well:var children = clean(this).getElementsByTagName('*');.the clean method also gets rid of any event handlers and storage attached to the child elements of the div.
THEN. events added by mootools go into element storage. Element storage is in an object behind a closure which the element proto uses. To test it, we will re-implement it and make it puncturable (a global object called storage) so we can check what happens to the reference after the parent is gone:
http://jsfiddle.net/dimitar/DQ8JU/
what all this proves is, mootools cleans up all you need cleaned. as long as you don’t use any inline
onclick=stuff on elements you work with, you’re going to be fine. Between mootools’ garbage collection and the browser, you are well covered. just be aware you can stack up multiple events on a single element if the callbacks are anonymous.