You could also eliminate that outer function by using Function.prototype.bind
(either the Prototype library version or the ECMAScript 5 native version if your browser supports it). For example:
function handler(myBoolean) {
console.log(myBoolean); // will output true
}
$(function() {
$('#test').click(handler.bind(this, true));
});
The first argument to bind
is the context you want to execute the function within. Subsequent parameters are passed to the handler
function. When jQuery executes handler
as a callback, the function calls are curried and the parameters it passes will be tacked onto the ones you specified in your bind
call. So, in my example handler
would receive three parameters when you click on #test
: the boolean you passed in, the event object, and the DOM element that was clicked.
jQuery has a rough equivalent of bind
with its function $.proxy
. By default, it doesn't allow you to curry functions like bind
does, but someone wrote an extension to it that will give it that functionality.
In my opinion, bind
is a better choice than $.proxy
since it has cleaner syntax, doesn't require you to monkey patch jQuery, and will be supported natively by browsers once ECMAScript 5 is fully implemented.