I have the following code:
function someMethod()
{
$(obj).click(function {});
}
someMethod is called twice and thus click event is binded
I was also trying to use off and on method of jquery for binding event only once with the dom element which does not exists yet or the dom element is not yet created.
$('.select').off('event').on('event', 'selector', function(e){ // });
This code was not working properly
I came across a very lucrative method that is 'one' method. It is very useful when you want to bind an event only once.
You can find the document here http://api.jquery.com/one/
This is same as method 'on' but different with its behavior with not to stick with the event for multiple selectors.
$('body').one('click', 'selector', function(){ // do your stuff here });
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
});
}
You can achieve this with pure JS, using addEventListener method and his once option
target.addEventListener('click', handler, {once: true});
You can add css class to the binded elements and then filter them out:
function someMethod()
{
$(obj).not('.click-binded')
.click(function {})
.addClass('click-binded');
}
This method may be used also for plugins:
$(obj).not('.datetimepicker-applied')
.datetimepicker()
.addClass('datetimepicker-applied');
There is no built in method to determine if you have already bound this particular function. You can bind multiple click functions to an object. For example:
$('#id').bind('click', function(){
alert('hello');
});
$('#id').bind('click', function(){
alert('goodbuy');
});
if you do the above when the object is clicked it will alert hello then goodbye. To make sure only one function is bound to the click event unbind the click event handler then bind the desired function like this:
$(obj).unbind('click').bind('click', function(){... });
jQuery makes calling some function possible only once pretty easy:
function someMethod()
{
$(obj).click(function() {});
this.someMethod = $.noop;
}