Jquery prevents function duplication

If I need to assign a click function dynamically, is there a way to ensure that the click function is only assigned once and not duplicated?

this.click(function(){ alert('test'); }) 
+19
function jquery dynamic click
Oct 13 '09 at 5:45
source share
4 answers

You can cancel the click event before binding it again, so you only have one event associated with it:

 //assuming this is a jquery object. this.unbind("click"); this.click(function(){ alert("clicked once"); }); 

As in jQuery 1.7, click .on now ( http://api.jquery.com/click/ ), so the correct code is now

 //assuming this is a jquery object. this.off("click"); this.click(function(){ alert("clicked once"); }); 

This will cancel all click events (including those created by any plugins that you could use). To make sure that you only cancel the namespace for event use. ( http://api.jquery.com/off/ )

 //assuming this is a jquery object. this.off("click.myApp"); this.on("click.myApp", function(){ alert("clicked once"); }); 

Here myApp is the namespace.

+34
Oct. 13 '09 at 5:47
source share

With jQuery . on () you can do something like this:

 //removes all binding to click for the namespace "myNamespace" $(document).off('click.myNamespace'); $(document).on('click.myNamespace', '.selector', function(event) {...}); //this will be also removed (same namespace) $(document).on('click.myNamespace', '.anotherSelector', function(event) {...}); 
+15
May 31 '12 at 21:20
source share

I would like to add to Marius the answer -

To avoid duplicate bindings, you do not want to accidentally undo something if it is assumed that there are several functions associated with the event. This is especially important when you are working on something with several developers. To prevent this, you can use the event namespace:

 //assuming this is a jquery object. var alertEvent = 'click.alert' this.unbind(alertEvent).bind(alertEvent,function(){ alert('clicked once'); }); 

Here "alert" is the namespace name for your click event, and only your functions associated with this namespace will be unrelated.

+9
May 9 '12 at 23:50
source share

assuming elements are added in html and you want to add an event only for added elements:

 function addEvents2Elements()//prevent Duplicate { //this will add the event to all elements of class="ele2addevent" $('.ele2addevent').not('.clickbind').on('click',function(){alert('once');}) //this will add a class an then the class="ele2addevent clickbind" $('.ele2addevent').not('.clickbind').addClass('.clickbind'); //all elements of class="... clickbind" will not be catched anymore in the first line because of .not() every time you call this function } addEvents2Elements(); 

be shure that you add only with class = "ele2addevent", because after binding there will be class = "ele2addevent clickbind" and will not be received again ...

0
Dec 26 '15 at 12:24
source share



All Articles