Delegates in JavaScript. Now with parameters.
August 28, 2006
Here is an extended delegate function:
function delegate( that, thatMethod )
{
if(arguments.length > 2)
{
var _params = [];
for(var n = 2; n < arguments.length; ++n) _params.push(arguments[n]);
return function() { return thatMethod.apply(that,_params); }
}
else
return function() { return thatMethod.call(that); }
}
And here is an example. Note that obj.method now accepts additional parameter p
var obj =
{
name: "someName",
method: function (p ) { alert( this.name + ":" + p ); }
}
function testIt()
{
window.setTimeout( delegate( obj, obj.method, "parameter!" ), 1000 );
}
Example of the delegate is delegate-test.
Note: this is so called parametrized delegate - parameters defined at the point of construction of the delegate - in delegate() call per se.
If you need delegate that will be inoked with parameters supplied by the caller you should use this one:
function delegate_cp( that, thatMethod )
{
return function() { return thatMethod.apply(that,arguments); }
}
So caller will call it as:
var d1 = delegate_cp( obj, obj.method );
...
d1( param1, param2 ); /* parameters for the delegate
call provided at the point of invocation. */

The delegate function is very useful. Thanks!
Comment by Enric — June 18, 2008 @ 8:17 pm
thx! this is very cool!
Comment by kfir — June 30, 2008 @ 5:06 am
A much more useful version which can be used regardless of situation
function delegate(obj, func){ var f = function() { var target = arguments.callee.target; var func = arguments.callee.func; return func.apply(target, arguments); }; f.target = obj; f.func = func; return f; }Comment by Drew Foehn — December 8, 2008 @ 5:07 pm
Yeah, not bad, not bad…
But this, I think, is even better:
function delegate(obj, func) { return function() {return func.apply(obj, arguments); }; }Isn’t it?
Comment by Andrew — December 8, 2008 @ 10:08 pm