tags:

views:

52

answers:

3

if you got something like this:

jQuery(selector).focus(function(){...});
jQuery(selector).focus(function(){...});

the focus will trigger twice, is there anyway that I can correct/prevent that?

+1  A: 

You can use unbind to remove the earlier handler. How you would use it depends exactly on why you are trying to avoid having both handlers fire in the first place.

I don't think that's a nice solution. I was thinking to check before binding if it was already binded, but I don't know how.
Adrian Crapciu
Can I ask exactly what you are trying to achieve here?
For example, often people try to do something similar to what you have asked so that when new elements dynamically appear on the page, you can attach the same event handlers to them without affecting the originals. But in that case, you should be using http://api.jquery.com/live/ instead.
I know about live/delegate, but it was something different. Anyway it works now, thanks for your help.
Adrian Crapciu
+1  A: 

Use the data('events') to find event handlers:

var isBound = function(el, ev) {
    var found = false;
    $.each($(el)).data("events"), function(i, e) {
        if (i === ev) {
            found = true;
        }
    });
    return found;
}

if (!isBound(selector, 'focus')) {
    $(selector).bind('focus', fn);
}

I think you can use the .one() function in jQuery too, have a look at http://api.jquery.com/one/

David
Thanks a lot .one() worked
Adrian Crapciu
It is extremely important to note that .one() only will ever fire once. So once it is executed it is unbound. If you like it to only ever be bounded once, however can be executed indefinitely then you can use jQuery Sparkle's once which works just like bind (however only ever binds once):http://github.com/balupton/jquery-sparkle/blob/9921fcbf1cbeab7a4f2f875a91cb8548f3f65721/scripts/resources/jquery.events.js#L41
balupton
+1  A: 

Try using event namespace and use bind:

var fnFocus = function(){ ... };
$(selector).bind('focus.namespace',fnFocus);

$(selector).unbind('focus.namespace').bind('focus.namespace',fnFocus);
jerjer