views:

108

answers:

3

For example if I have a link with the following event bound to it:

$("a.d").bind("click", this, onDelete);

And later do:

$("a.d").remove();

Is that fine? Or does it cause a memory leak and I need to call unbind 1st?

Thanks for any help.

+4  A: 

I haven't tested it, but I believe that removing an element will unbind its event handlers. I come to this conclusion from the jQuery API documentation (search for remove) which states that if you want to move an element from one part of the DOM to another that:

$("#foo").remove().appendTo("#bar");

should be written as

$("#foo").appendTo("#bar");

to avoid losing the event handlers.

Phil
+6  A: 

From jQuery docs for remove()

Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use the matched elements further. Note that this function starting with 1.2.2 will also remove all event handlers and internally cached data.

code_burgar
+1 for "insider info" :)
Here Be Wolves
A: 

For the record, you need not worry about memory leaks in javascript. (chill man, not c++!)

The browser's javascript engine manages all objects, and garbage collects them. When I say objects, that means event-handling-functions too, because functions are also objects in javascript.

Unrelated: I love how everything is an object in javascript :D

Cheers!
jrh

Here Be Wolves
Not true actually, you can very easily create memory leaks in javascript if you create closures. Poor event management is one place where memory leaks are common. Certain js engines are better than others, for example, Chrome's V8 seems to garbage collect the closures properly. However, Firefox (at least 3.0, haven't tried it with 3.5), and IE can and do have memory leaks in javascript.
TM
FYI the reason I know this is because I've run into it before (I even asked about it on SO, see this old question of mine: http://stackoverflow.com/questions/276087/preventing-ajax-memory-leaks)
TM
-1 It may not be C++ but it certainly can leak memory!
Josh Stodola
Hmm.. thanks for the info guys
Here Be Wolves