MooTools: Element disposal
Let's say I have two elements on a page. One is a div, and the other is its child, an achor. Let's say that I've added an event to that anchor via开发者_如何学JAVA anchor.addEvent('click', ...)
. If I set the div's .innerHTML = ''
, does the 'click
' event associated with the anchor get removed/disposed of/garbage collected?
It depends if you have still reference to "anchor" DOM instance. If so, it will stay in memory until all references are removed.
Test example:
var parent = new Element('div');
var child = new Element('div', {
events : {
click : function() {
alert('child clicked');
}
}
});
child.innerHTML = 'child content';
parent.appendChild(child);
document.body.appendChild(parent);
parent.innerHTML = 'parent content';
document.body.appendChild(child);
According to the MooTools API: destroy()
is a method that:
Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.
I suspect that what happens to anchors removed when their parent elements are removed using innerHTML = ''
is going to depend on the browser.
jQuery offers an empty()
method, I am guessing other libraries probably offer methods too. You can see a pretty good discussion of this topic in Removing an element from DOM.
- IMHO, you should use empty() instead of innerHTML = "".
- The reference will remain like @nemisj said, but it will be "floating" and useless. I did some tests here: test case, maybe you'll find interesting.
精彩评论