Dharman
Dharman

Reputation: 33242

bind one handler to many events

How can I bind one handler to many events and make sure that the handler is called only once even if more than one events were fired?

$(".element").bind("click select" ,handl);
function handl (e) 
{ 
     //my code
}

The problem with this code is that the handl is called twice for each event. If you think that the handler should only be called once if both events are fired than please tell me so because I think that the handler in this code should be called twice.

Upvotes: 1

Views: 90

Answers (2)

jzilla
jzilla

Reputation: 1703

use a closure to wrap your event function like this

$("#a").bind("click focus", function () {
    var fired = false;
    return function() {
        if (!fired) {
           alert("click occured");
           fired = true;
        }  
    } 
}());

jsfiddle of it here

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

I am not sure if I understood correctly.. but I am assuming that you are trying to prevent multiple events calling the handler function multiple times from one user action.

var isExecuting = false;
$(".element").bind("click focus" ,function () {    
    if (isExecuting) return false;
    isExecuting = true;
    handl.call(this); //maintain the context
    isExecuting = false;
});
function handl (e) 
{ 
    //your code
}

Upvotes: 4

Related Questions