Delegates in JavaScript. Now with parameters.

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. */
  

4 Replies to “Delegates in JavaScript. Now with parameters.”

  1. 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;
    }
  2. 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?

Comments are closed.