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 {...
Hi thanks for this but this code doesn’t work for me ( I’m using Flash Cs4 Portable version, using as exportation parameter flash player 9 and as2 )…this code did works for you?, what flash version do you have ? I was trying to implements this code on a textfield events (focus and kill) and i was trying to pass some parameters and the first parameter that i got was always the lattest selected textfield.. So anyway using this code as template i implement this code that i post here, i don’t know if this code its okey (but again) works really well for me , i dont know if this works for you as well as your original code posted here.. Anyway Thank’s again for post this code.
public static function DelegateCreate(t:Object, f:Function,args:Array):Function
{
return function():Void
{
//i prefer pass the args as one explicit array. just for practical reasons.
if ((args == undefined) || (args == null))
args=[]
//I just change the order of the arguments.! First the arguments that i pass and after well the rest.!
var _newArgs:Array = args.concat(arguments);
f.apply(t, args);
};
}