3

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MQ87
  • 1,008
  • 1
  • 13
  • 30
  • 1
    Here you are binding events using jQuery. You don't have to unbind any event in your case, jQuery handles it and it would be the same here using vanilla js relevant method anyway (without using any referenced object). That's said in your case you'd have better to delegate event to static `#wrapper` element, this would just bind one event handler handling all children `.eventDiv` elements. – A. Wolff Oct 25 '15 at 13:02

1 Answers1

0

Consider this example:

http://jsbin.com/bunoyedabo/edit?html,js,console,output

First of all, use event delegation. $().on('eventName', 'targetSelector', cb); Second is that you can unbind events using .off() or .unbind().

blade091
  • 642
  • 4
  • 10