My question is simple: Do we have to remove Javascript events listeners from elements that we are removing dynamically from the DOM?
Let's take this example (fiddle with full code) using jQuery: we have a user action that changes the DOM content using jQuery html
function:
$('wrapper').html(markup);
The markup variable has got a lot of elements with the class eventDiv
, and on those elements we add some event listeners:
$(".eventDiv").mouseenter(function() {
$(this).css('background-color', 'red');
});
$(".eventDiv").mouseleave(function() {
$(this).css('background-color', 'white');
});
Does this way of changing html content lead to a memory leak? Do we have to unbind all the event listener? Or is the removing of the nodes from the DOM enough?
And second, there is an easy way to remove all the listener on child element of a container div? In my case something like
$('wrapper').unbindAllChildEventsListeners();
PS: this is a example, the real case scenario has got a lot of different events on the new markup that is loaded by the user action, and also a DOM tree much more articulated, the "markup" variable is coming from a dustjs template.