Does jQuery overwrite event listeners?

I've got a bunch divs which each contain a remove link attached with the click event below:

  var observeRemoveRoom = function

Clicking it removes the 'active' class of the parent (the div). I call this observeRemoveRoom function on window load which works fine.

The thing is, I have another function which adds more of the same divs. Since the 'a.remove_room' links contained within the new divs weren't around on window.load I need to call observeRemoveRoom.

Am I somehow duplicating the event handlers? Does Jquery overwrite them? If so should I unbind the handlers?



Each time you call observeRemoveRoom jQuery will add a new unique event handler function for a click event.

So yes, you need to .unbind() either all currently bound handlers by just calling .unbind() without arguments, or be specific and pass in a function reference.


You can try a live query to keep them updated:


Yes, you will be duplicating the event-handlers if you call observeRemoveRoom again, but it might not be noticeable since you are only calling the removeClass method which does nothing if the class is not found, which would be the case after the first listener is triggered.

Instead you can un-bind and re-bind the click event each time, like:

 var observeRemoveRoom = function(){
    var remove_class = function(){     
    $('.remove_room').off('click', remove_class).on('click', remove_class);

But that said, it is recommended that you do this outside this function`, rather than binding and unbinding the event every time, like:

    var remove_class = function(){     
    // If the element exists at dom ready, you can bind the event directly
    $('.remove_room').on("click", remove_class);
    // If the element is added in dynamically, you can [delegate][1] the event
    $('body').on("click", '.remove_room', remove_class);
    // Note: Although I've delegated the event to the body tag in this case
    // I recommend that you use the closest available parent instead
}); : [1]


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.