Araklaj Araklaj - 5 months ago 9
Javascript Question

Passing anonymous functions through jQuery event call without eventData

Given an

<input id="foo">
element, I want to call an existing function on blur and pass an anonymous callback to it.

Case 1, simple function call:

function bar(){
alert("I am");
}

$("#foo").blur(bar); //Works fine


Case 2, passing arguments/function:

$("#foo").bind("blur", {func: function(){console.log("I am apple")}}, bar);

function bar(event){
event.data.func(); //Works fine
};


Problem with case 2 is that I'd like to have
bar()
as a generic function called by more than blur, in which case I would be passing anonymous function directly, not "baked" into a data object. So ideally like this:

function bar(callback){
//Do stuff
callback();
}

bar(function(){console.log("Hello Earth")}); //Works

$("#foo").blur(bar(function(){console.log("Hello world")})); //Doesn't work


Last line doesn't work as function gets executed directly, but it's an example of what I would like to achieve. I guess I possibly could make some typeof checks in
bar()
to determine what I am receiving, but I wanted to ask if there's a cleaner way to pass anonymous function on blur, instead of changing
bar()
.

Answer
function bar(callback){
    //Do stuff
    callback();
}

bar(function(){console.log("Hello Earth")}); //Works

$("#foo").blur(bar.bind(this,function(){console.log("Hello world")})); //Will work