sholsinger.com

Categories Photography Résumé About Me

Prevent jQuery.live() Handlers From Firing Multiple Times

05 Aug 2011

Recently I was working on something where I needed to use jQuery's .live() event handling. The problem I was experiencing was that my .live() 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 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 property to the jQuery event object. My event handler method then checks to see if this property is equal to true and if it isn't, then it executes it's payload. Otherwise it just returns false to prevent bubbling.

function myLiveEventHandler(event)
{
  if(event.handled !== true)
  {
    // put your payload here.
    // this next line *must* be within this if statement
    event.handled = true;
  }
  return false;
}

$('selector').live('event', myLiveEventHandler);

There you have it. We have bound a .live() event handler and prevented it from running twice. (If it just so happened that it were bound more than once.) 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 the poor man's way of handling this problem and you should probably try to find a way to avoid double binding the event instead. Who has the time for that?

Filed under

Comments
comments powered by Disqus