views:

1314

answers:

3

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.

+3  A: 

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);
tvanfosson
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)
Mark Renouf
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.
tvanfosson
+1  A: 

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);
Mark Renouf
Thanks, it works now :)
shuxer
+7  A: 

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
moff