bind event only once

前端 未结 13 2101
予麋鹿
予麋鹿 2020-12-05 03:45

I have the following code:

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

someMethod is called twice and thus click event is binded

相关标签:
13条回答
  • 2020-12-05 04:30

    The obvious solution is to not call someMethod() twice. If you can't fix that, then you can keep a state variable so it only ever binds once like this:

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

    Note: this uses a property of the function itself rather than introducing a global variable to keep track of whether it's been bound. You could also use a property on the object itself.

    You can see it work here: http://jsfiddle.net/jfriend00/VHkxu/.

    0 讨论(0)
提交回复
热议问题