Considering this code:
$("#divToBeClicked").on('click', function(e){
 // large pile of code
});
The 'e' parameter is passed by the on() method. I need to split the code inside this function to a different function, as it is too large. Now, this would work just fine:
$("#divToBeClicked").on('click', function(e){
 otherFunction(e, param2, param3);
});
But as I'm curious, I was wondering how to do it the following way:
$("#divToBeClicked").on('click', otherFunction(e, pararm2, param3));
How, if possible, do I accomplish this? If I try it this way, e is undefined in otherFunction(). Notice that I'm passing extra parameters to this function.
4 Answers 4
You can either pass it in as data which is available on the event object
function myfunc(e) {
 console.log(e.data);
}
$("button").on("click", {"a" : "apple", "b" : "box"}, myfunc);
or use a closure
function myfunc(e,a,b) {
 console.log(a);
}
var x = "apple", y = "box";
$("button").on("click", function(e){ myfunc.call(this, e, x, y) });
You could also bind/jQuery.proxy, but you lose "this" pointing to what was clicked.
Comments
If you want to replace the anonymous function with your function you simply omit the () - but your function must take the same params that the anonymous would (event, not sure what param1 and param2 are):
$("#divToBeClicked").on('click', otherFunction);
And otherFunction:
function otherFunction(e) {
 console.log(e); //theres e
} 
If you want the extra params, you need the anonymous function:
$("#divToBeClicked").on('click', function(e){
 otherFunction(e, param2, param3);
});
Edit: Corrected, you can use .bind
8 Comments
You can use the Function.bind() like
$("#divToBeClicked").on('click', otherFunction.bind(undefined, pararm2, param3));
Note: this inside the handler will no longer refer to the clicked element, also supported only from IE9+
Comments
This looks like a good use case for bound functions.
The only problem is that you will need to switch around the order of parameters for otherFunction, so that the event is the last one.
$("#divToBeClicked").on('click', otherFunction.bind(window, pararm2, param3));
In this snippet, i bind the context of otherFunction to window (the default). Then, i specify a default first two parameters for it.
Note that here the context (this) of otherFunction won't be the element that the handler was called on; but since your original solution of an anonymous function lost it anyways, it doesn't seem like a problem.
$("#divToBeClicked").on('click', otherFunction);. And I think you need a selector after the event.