Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

The answer is yes, so long as the event was attached WITH jQuery. If attached with something like "onclick" I don't believe it will.

This article discusses some of that. It also defines a recursive function to remove all click events for an element and all of its children. It will cover jQuery click handlers as well as handlers defined with onclick so you're covered.

http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/

function RecursiveUnbind($jElement) {
    // remove this element's and all of its children's click events
    $jElement.unbind();
    $jElement.removeAttr('onclick');
    $jElement.children().each(function () {
        RecursiveUnbind($(this));
    });
}

To use the function in the previous example we would call the function passing it the “container” div as a jQuery object.

RecursiveUnbind($('#container'));

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top