How to prevent multiple attachment of an event handler?

I have a function that binds a click event handler to my element:

 function attachClickToElem() { $('.elem').on('click', function () { alert('Hello World'); }); } 

The problem is that whenever I call this function, n click attaches to my element, so when I call it twice, I get two alert when I click on my element:

 $(function () { attachClickToElem(); attachClickToElem(); }); 

How can I prevent this? And make sure my element is already a click handler?

Here is the fiddle

+7
source share
3 answers

JsFiddle working demo

Use the .each() method to scroll .each() your elements, and check the flag for event handlers already using .data() , if true , skip the current loop. Otherwise, attach an event handler to the element and set the flag to true .

 function attachClickToElem() { $('.elem').each(function () { var $elem = $(this); // check if event handler already exists // if exists, skip this item and go to next item if ($elem.data('click-init')) { return true; } // flag item to prevent attaching handler again $elem.data('click-init', true); $elem.on('click', function () { alert('Hello World'); }); }); } 

Literature:

+4
source

Try

 function attachClickToElem() { $('.elem').off('click.mytest').on('click.mytest', function () { alert('Hello World'); }); } $(function () { attachClickToElem(); attachClickToElem(); }); 

Demo: Fiddle

Another way

 function attachClickToElem() { $('.elem').filter(function(){ return !$(this).data('myclick-handler'); }).on('click.mytest', function () { alert('Hello World'); }).data('myclick-handler', true); } $(function () { attachClickToElem(); attachClickToElem(); }); 

Demo: Fiddle

+11
source

Something close to this I believe:

 function attachClickToElem() { $('.elem:not(.has-click-handler)') .addClass('has-click-handler') .on('click', function () { alert('Hello World'); }); } 
0
source

All Articles