2

It's a small question yet important.

Should I run .unbind('click') before doing e.g. button.click(... ?

Basically, if there's an event defined for a control, am I supposed to unattach it before attaching it again? I know this is the case for those that I add using 'bind()'...

IamDeveloper
  • 5,156
  • 6
  • 34
  • 50

1 Answers1

2

I know this is the case for those that I add using 'bind()'...

click(func...) is just a shortcut for bind('click',...).

If you assign the same handler to the control, then you should remove it before attach again. Otherwise the handler will be executed more than once.

If you have a reference to the handler anyway you can just do:

$element.unbind('click', handler);

This removes only the event handler handler and leaves all the others intact.


Maybe interesting in this context are event namespaces:

If you want to bind multiple event handlers to an element but you want to prevent rebinding the same event handler (and you have no reference to the original handler), you can use namespaces:

$element.bind('click.onlyone', function()...);
$element.unbind('click.onlyone');
//or $element.unbind('.onlyone');
$element.bind('click.onlyone', function()...);

Update:

bind will not remove previous handlers. So if you don't want them to be triggered, you have to unbind them first...

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • thanks for a detailed anwer, but please just answer with yes or no. If I use button.click(function(){...}) , do I have to do button.unbind('click') before assigning click again (which may have a little bit different handler, cause it's dynamic)? – IamDeveloper May 04 '11 at 11:18
  • @IAmDeveloper: Only if you don't want to keep the previous handler. There is no simple Yes or No. It depends on what you want and you did not state this. – Felix Kling May 04 '11 at 11:19