0

if we attach a delegated event with jquery .on() like

$(".container").on("click", "#testDiv", function (event){
  console.log(event);
});

and latter in the script if i remove the #testDiv element with jquery .remove() as,

$("#testDiv").remove();

then will it create any memory leak or not...

atul bajpai
  • 155
  • 1
  • 1
  • 7

1 Answers1

0

Well, since you're using a delegated event attached to .container, your event listener will NOT be removed.

Like documentation says:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

This means that whenever a click event is triggered inside .container, will always execute a query to check if the clicked element is #testDiv

This can't be defined memory leak, because it's exactly how is supposed to work event delegation. Read this post where is explained performance differences between event delegation and direct binding.

Anyway, if you don't need that listener anymore you can either:

  • call .off() function to manually remove the listener before removing the element
  • or just don't use event delegation if you don't really need, but direct binding
Community
  • 1
  • 1
pumpkinzzz
  • 2,907
  • 2
  • 18
  • 32
  • thanks @pumpkinzzz, just one more query, in my case i have similar hundred's of event, and their respective element can be remove or added dynamically based on the user interaction. so what is the better way of handling it, should i remove the event when the element is removed and add the event back when it is added again... – atul bajpai May 30 '16 at 14:03
  • @atulbajpai nope, if you have hundred of events just keep using delegated events, it's totally fine. See my updated answer – pumpkinzzz May 30 '16 at 14:17