You've got a lot of Gal

Yet another blog about Ruby, Rails, Javascript, Apple, Malteses and Shih-Tzus by Gal Steinitz

This site is completely static. It was last generated with Octopress and Jekyll on Sep 02, 2013 and hosted on github pages.

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.