开发者

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.


  1. IMHO, you should use empty() instead of innerHTML = "".
  2. 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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜