Alex Rivera | Logout

bind event only once

Asked 2011-12-07T00:21:23.340
115

I have the following code:

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

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

Edit
Report

3 Answers

20

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(){... });
answered 2012-10-23T16:48:10.833
5

jQuery makes calling some function possible only once pretty easy:

function someMethod()
{

     $(obj).click(function() {});
      this.someMethod = $.noop;
}
answered 2011-12-07T00:35:35.877
1
var bound = false;

function someMethod()
{
    if(!bound)
    {
       $(obj).click(function {});
       bound = true;
    }
}

but I would probably look into why it;s being called twice before making some kind of workaround.

answered 2011-12-07T00:24:34.253

Your Answer