Preventing duplicate event handlers in jQuery

I was working on some plugin development lately and ran into an issue where I needed to remove any event handlers already attached to an element before attaching a new one. I found the easiest way to do this was to simply “unbind” any previous handlers directly before binding the new one:

$("#someid").die("click").live("click",function(){...

or

$("#someid").unbind("click").bind("click",function(){...

If you’re using a more recent jQuery version (1.7+) then you may/should be using the ‘on’ event to attach events. If this is the case then you can use ‘off’ immediately before hand to unbind the event, like so:

$("#someid").off("click").on("click",function(){...

One much appreciated response...

  1. Martins says:

    Excelent!

Feel free to add your comment..

Your email address will not be published.