Search code examples
javascriptjqueryjquery-eventsjquery-click-event

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
    $('.remove_room').click(function(){     
      $(this).parent().removeClass('active');
    });
  }

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?


Solution

  • 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.