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?
Syntax: $(". event-handler-btn"). one("click", function (e) { // Code to be executed once });
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 }); }
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With