开发者

jQuery/javascript - Wire up event handler only when its not already assigned

开发者 https://www.devze.com 2023-02-22 17:54 出处:网络
I\'m assigning an onclick handler to a checkbox. Sometimes javascript that does the binding of event runs more than once (on partial postbacks) and the handler gets assigned twice. How can I prevent t

I'm assigning an onclick handler to a checkbox. Sometimes javascript that does the binding of event runs more than once (on partial postbacks) and the handler gets assigned twice. How can I prevent the handler from being assigned multiple times?

Okay thanks for responses. I wrote something up to figure out if element has a hanlder:

$.fn.hasHandler = function(eventName, handler)
{
    var _hasHandler = false;

    if(handler != undefined && this.data("events") !== null && this.data("events") !== undefined)
    {
        $.each(this.data("events"), function(name, handlers)
        {
            if(name === eventName)      
            {
                $.each(handlers, function(index, value)
                {
     开发者_Python百科               if(value.handler === handler)
                    {
                        _hasHandler = true;
                    }
                });
            }
        });
    }

    return _hasHandler;
}


You can unbind first.

$('#foo').unbind('click').bind('click', function(){...do stuff here...});


Assuming you have:

<input type="checkbox" id="myCheck" />

Your javascript might be:

var clickFound = false;
$.each($("#myCheck").data('events'), function(i, e) {
    if(i === 'click') {
        clickFound = true;
    }
});
if(!clickFound) {
    $("#myCheck").click(function() {
       // ...
    });
}

See more on testing for events bound via jQuery at this question.

Is there a reason, though, you can't use delegate or the older live to allow your handler to be bound once and then to persist for all matched elements?


You could add a class to your checkbox when you add the click handler, and then later check for the existence of the class.

You could also unbind the click handler before adding one as an alternative.

Or, probably the cleanest thing to do would be to prevent your code from running twice.

0

精彩评论

暂无评论...
验证码 换一张
取 消