Wednesday, April 6, 2011

How to overwrite jquery event handlers

I'll try to explain the problem with a simple code.

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').click(fireclick);

So now it will obviously alert 2 times but i need it alert only once. Tried so many ways, but no result.

Thanks.

From stackoverflow
  • If you want to replace all click handlers, call unbind first without a function argument. If you want to replace all event handlers, don't specify the event type.

    $('#clickme').unbind('click').click(fireclick);
    $('#clickme').unbind('click').click(fireclick);
    
    Mark Renouf : Bah! You win for chaining the call, but maybe refine your answer so it only removes the specific handler being re-added? So: $('#clickme').unbind('click', fireclick).click(fireclick)
    tvanfosson : The question was "overwrite jquery event handlers" -- I was assuming that he wanted to replace them all. To do that he needs to call unbind each time (which is why I repeated the call on both) and not specify a function argument.
  • I would try to eliminate the extra calls, but short of tyhat you could make sure to call both of these each time:

    $('#clickme').unbind('click', fireclick);
    $('#clickme').click(fireclick);
    
    shuxer : Thanks, it works now :)
  • You may use the jQuery function unbind to remove the first event:

    var fireClick = function() { alert('Wuala!!!') };
    
    $('#clickme').click(fireclick);
    $('#clickme').unbind('click', fireClick); // fireClick won't fire anymore...
    $('#clickme').click(fireclick); // ...but now it will
    

0 comments:

Post a Comment