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?
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.
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.
The off() method is most often used to remove event handlers attached with the on() method.
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.
According to jquery docs:
In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With