开发者

jquery multiple binds

fellow coders, assuming that I have a button with a click handler like so:

$("#save-item-btn").click(function() { saveItemDialogData(true); });  

if the same code is executed again, would jquery realize that, clear the previous bind and reapply it or would it consume resources or cause unnece开发者_如何转开发ssary side effects?

thanks


If the function is bound twice, the function will be added twice, and execute twice on every click event.

If you need to make sure that you're not re-binding the function 100 times, unbind the function before re-binding:

$("#save-item-btn").unbind('click', doSave).click(doSave);

function doSave()
{
  saveItemDialogData(true);
}


Every time you call click(), it will bind the function you give it to that handler -- it can't tell that the function is the same. If you want to be sure that there are no prior click handlers on your button, first call unbind('click') on it and then attach your click handlers.

Note that assigning to the onclick property directly will replace the existing handler with whatever you assign to it; allowing multiple functions to be bound to the same event is a jQuery feature.


If this code will be executed again the new function will be added to click queue. As @Faisal noticed you can call unbind in order to remove handler but it could remove usefull handlers from other parts of app, so you probably should use handler namespaces like this:

$(selector).unbind('click.mynamespace');
$(selector).bind('click.mynamespace', myhandler);

this way you will only replace your own handler


It will attach a second click event handler and leave the original handler. In that case you are specifically using an anonymous function, jQuery couldn't possibly know if a similar function is already attached or not to the element.

You can use unbind to detach previous handlers. It's preferable to use Namespaced events as described here: http://docs.jquery.com/Namespaced_Events.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜