Javascript Pattern for Passing Additional Variables Into an Event Handler
When you need to pass extra variables into your event handler, you can’t just pass it in since the event handler has a specific signature (function (e){}). However there are several options: Thanks to Javascript Closures, anonymous functions do have access to their original scope and variables, so something like this would work:
[sourcecode language=”jscript”]
var myVar = "Hello!";
$("#element").click(function(e){
alert(myVar);
});</code>
[/sourcecode]
However, this alternate pattern is a bit cleaner and makes it obvious which variables your event handler depends on:
[sourcecode language=”jscript”]
var myVar = "Hello!";
$("#element").click(clickHandler(myVar));
function clickHandler(myVar) {
return function(e) {
alert(myVar);
}
}
[/sourcecode]
Keep in mind that in this second pattern, clickHandler is actually called at parse time and not when the event fires. When it gets called, it returns the anonymous function which is what actually gets bound to the event and gets called when the event fires.