Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to unbind events from elements removed from a document

I am using JQuery, and I would like to know if the remove() method cleans its contents of event handlers. For instance:

function someFunction() {
    var element = $('<div></div>');
    element.click(function() {
        alert('bar');
    });
    $('body').append(element);
    element.remove();
}

At this point is there an event handler still hanging out in memory? If so, is there a way to clear the element object of event handlers before removing it from the DOM?

like image 730
dqhendricks Avatar asked Aug 26 '11 00:08

dqhendricks


People also ask

Are event listeners removed when element is removed?

In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.

What is the use of unbind method?

The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

Which event method is used to remove event during execution?

The off() method is most often used to remove event handlers attached with the on() method.

What is bind and unbind in jQuery?

jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.


1 Answers

According to jquery docs:

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

like image 125
Derek Hunziker Avatar answered Nov 09 '22 13:11

Derek Hunziker