开发者

jQuery's (ui) general approach to unbinding events?

It's a small question yet important.

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

Basically, if there's an开发者_Go百科 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()'...


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...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜