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!
thx! this is very cool! 🙂
A much more useful version which can be used regardless of situation
Yeah, not bad, not bad…
But this, I think, is even better:
Isn’t it?