Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind event only once

Tags:

jquery

I have the following code:

function someMethod() {   $(obj).click(function {}); } 

someMethod is called twice and thus click event is binded twice. How can I make it bind only once?

like image 781
firebird Avatar asked Dec 07 '11 00:12

firebird


People also ask

How do you attach a event to element which should be executed only once jQuery?

Syntax: $(". event-handler-btn"). one("click", function (e) { // Code to be executed once });


2 Answers

If you can apply it, probably want to take a look at event.preventDefault and event.stopPropagation OR unbind and bind each time, within your method like

function someMethod() {   $(obj).off('click').on('click', function(e) {     // put your logic in here    }); } 
like image 84
pna Avatar answered Oct 14 '22 15:10

pna


In addition to pna's answer you may wish to think about namespacing your event so you do not go around unbinding all the click events accidentally.

 function someMethod() {     $(obj).unbind('click.namespace').bind('click.namespace', function() { }); } 

https://api.jquery.com/event.namespace/

like image 40
Iain Avatar answered Oct 14 '22 15:10

Iain