How to make jQuery `bind` or `on` event handlers idempotent

懵懂的女人 提交于 2019-12-13 14:35:18

问题


Is there a way that I can call $(selector).bind('click', handler) or $(selector).on('click', handler) multiple times such that the handler only gets attached once?

Right now, I have multiple AJAX handlers with different success callbacks, each of which re-renders a different set of elements on the page. Ideally I'd like to refactor the "reattach events" routine to a single function rather than a routine for all.

The only way I can think of to do this right now is to explicitly unbind, for example:

$(selector).off('click');
$(selector).on('click', handler);

Looking for a way to do something like that automatically.


回答1:


A better approach is just to move the .on call to a container. If you have a container, the .on sticks around and is applied to any existing or new children matching your selector:

$(container-selector).on("click", "element-selector", function(event){
// do stuff
});

http://api.jquery.com/on/

Cheers.




回答2:


You can namespace your event handlers, and then just make sure you unbind before binding:

$('#something').unbind("click.some-feature").bind("click.some-feature", function() { ... });

You could write your own jQuery function to do that automatically:

$.fn.schneiderBind = function(name, fn) {
  return this.unbind(name).bind(name, fn);
});

$('#something').schneiderBind("click", function() { ... });

Alternatively, you can use bubbling and delegation to bind higher in the DOM, at a point immune to dynamic updates.




回答3:


$(document).on("click","selector", function() {  code goes here... });

This will work with dynamically added objects



来源:https://stackoverflow.com/questions/12322607/how-to-make-jquery-bind-or-on-event-handlers-idempotent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!