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

Is there a way that I can call $(selector).bind('click', handler) or $(selector).on('click', handler) several times so that the handler only binds once?

I currently have several AJAX handlers with callbacks with different successes, each of which re-displays a different set of elements on the page. Ideally, I would like to reorganize the "repeat events" subroutine into one function, rather than the usual for everyone.

The only way I can do this now is to explicitly untie it, for example:

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

Looking for a way to do something like this automatically.

+3
javascript jquery javascript-events idempotent
source share
3 answers

It is best to move the .on call to the container. If you have a container, .on applies and applies to any existing or new children matching your selector:

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

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

Greetings.

+4
source share

You can use the namespace for event handlers, and then just make sure you untie before binding:

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

You can write your own jQuery function to do this 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 above in the DOM at a point independent of dynamic updates.

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

This will work with dynamically added objects.

-one
source share

All Articles