jQuery
New Wave Javascript


discuss » Binding events to newly added DOM elements


Posted: Sat Mar 11 03:27:50 EST 2006
From: Michael Geary <Mike at Geary.com >

> From: John Resig
>
> Just to clear up this thread - I've fixed the clonenode issue
> so that you can now create a DOM Element, attach an event,
> and append/prepend/etc it to a single Element - and it should work.
>
> A quick test case can be found here:
> http://jquery.com/test/clonenode.html

Great news on the cloneNode fix! That will let me clean up some of my code
that now uses $().get(0).appendChild.

But yowch... There are three memory leaks in the test case:

$(document).ready(function(){
var a = document.createElement("a");
a.innerHTML = "some contents";
a.href = "";
a.onclick = function() {
alert("It worked!");
return false;
};
$(document.body).prepend(a);
});

* DOM insertion order. Easy to fix this one, just move the a.onclick
assignment after the prepend instead of before.

* Circular reference on the event handler. Could use my $.closure fix that
I'm using and have been meaning to release, or do the remove handlers on
unload thing like you mentioned a while back. (I tried to get that to work
without success, so I stuck with the $.closure wrapper for now.)

* Setting a.innerHTML. Believe it or not, that leaks. (This really surprised
me; I haven't seen it mentioned anywhere, unlike the other well-known
leaks.) Use my DOM creation plugin and you can change this code:

var a = document.createElement("a");
a.innerHTML = "some contents";
a.href = "";

to this, which uses createTextNode/appendChild instead of innerHTML:

var a = $.A({ href:"" }, "some contents" );

I know, it's just test code, but it was amusing to see that leak-per-line
ratio. :-)

-Mike