Select Page

AS2.0 Delegate.create with parameters

This is an oldie but a goodie.
Getting around scope problems in AS2 can be a pain, but mx.utils.Delegate can help. The only problem is that you can’t pass parameters to your function using this one. The following class enables you to use the Delegate.create method, and also pass parameters to the function:

class com.sitedaniel.utils.Delegate
    public static function create(t:Object, f:Function):Function
        var _args:Array = arguments.slice(2);
        var _func:Function = function():Void
            var _newArgs:Array = arguments.concat(_args);
            f.apply(t, _newArgs);
        return _func;

UPDATE 11/10/08

This post gets quite a bit of traffic so I thought I should add a usage example.

This is a function that creates 5 buttons and spaces them in a loop:

private function _createButtons():Void {
    for (var i:Number = 0; i<5; i++) {
        var tmp:MovieClip = _mc.createEmptyMovieClip('b_'+i, i);
        tmp._x = 40 * i;
        tmp.onRelease = Delegate.create(this, _onRelease, i);

Delegate.create(this, _onRelease, i);

Then by passing 'i' in as a parameter, it comes into the function as an argument:

private function _onRelease(n:Number):Void {
    trace('_onRelease : '+n)

You can also pass in multiple arguments, including different types:

tmp.onRelease = Delegate.create(this, _onRelease, i, true, {val:10});
function _onRelease(n:Number, isGood:Boolean, myObj:Object):Void {...