Delegates in JavaScript. Now with parameters.

August 28, 2006

Filed under: Philosophy,Script — Andrew @ 10:45 am

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