1

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)
                {
                    if(value.handler === handler)
                    {
                        _hasHandler = true;
                    }
                });
            }
        });
    }

    return _hasHandler;
}
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247
  • If you're looking at partial post backs, are you re-assigning the handler because the element has been recreated? – StuperUser Apr 06 '11 at 15:15
  • IMO you need to improve your structure a bit as assigning events in JS code which is rendered on partial postbacks isn't really a good idea. I would love to know your use-case why you can't pull the event code to applicaton wide javascript? – neebz Apr 06 '11 at 15:21

3 Answers3

4

You can unbind first.

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

tengoal
  • 148
  • 6
  • 1
    Although `unbind(eventName)` will unbind ALL click event handlers. If the function is stored in a variable, it can be unbound individually. – StuperUser Apr 06 '11 at 15:45
  • this could be a easier fix but that doesn't answer my original question. thank you though. – dev.e.loper Apr 06 '11 at 22:22
1

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.

wsanville
  • 37,158
  • 8
  • 76
  • 101
1

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?

Community
  • 1
  • 1
justkt
  • 14,610
  • 8
  • 42
  • 62