Recently I was working on something where I needed to use jQuery's
.live()</code> event handling. The problem I was experiencing was that my
.live()</code> handler was firing multiple times for the same event. I devised a rather simple way to avoid this issue and I'm going to share it with all of you.
The first thing we need to know is that the
event</code> object which is passed to all of the event handlers for that given event is the same object. You can modify it and the next handler will get the same object you just modified. So my method takes advantage of that fact and adds a
.handled</code> property to the jQuery
event</code> object. My event handler method then checks to see if this property is equal to
true</code> and if it isn't, then it executes it's payload. Otherwise it just returns false to prevent bubbling.
if(event.handled !== true)
// put your payload here.
// this next line must be within this if statement
event.handled = true;
There you have it. We have bound a
.live()</code> event handler and prevented it from running twice. (If it just so happened that it were bound more than once.)</em> Why might it be bound more than once? If you use jQuery Mobile or some sort of AJAX loading method for content then you may duplicate your event handler binding every time you load a new page. This is probably</strong> the poor man's way of handling this problem and you should probably</strong> try to find a way to avoid double binding the event instead. Who has the time for that?