I hesitate to post this as I know its not a preferred way of using this especially if you’re building a flash app with strict Design Patterns. With that said, I really like using the Delegate Class, but as I’ve found a number of posts about not being able to pass an argument when using Delegate.create(obj,func);. I too wish there was some type of support for this (and I realize there are other ways of achieving this with Event handlers etc). Anywho, I have added to the Delegate class to support this. Getting the arg out is hacky, but for some very small classes I’ve build, it works well.
This is what I’ve added to the Delegate Class file:
[AS]
/**
The Delegate class creates a function wrapper to let you run a function in the context
of the original object, rather than in the context of the second object, when you pass a
function from one object to another.
*/
class mx.utils.Delegate extends Object
{
/**
Creates a functions wrapper for the original function so that it runs
in the provided context.
@parameter obj Context in which to run the function.
@paramater func Function to run.
//ADDED
@paramater args array to pass to Function.
*/
static function create(obj:Object, func:Function, args:Array):Function
{
var f = function()
{
var target = arguments.callee.target;
var func = arguments.callee.func;
return func.apply(target, arguments);
};
f.target = obj;
f.func = func;
//ADDED function.args
f.args = args;
return f;
}
function Delegate(f:Function)
{
func = f;
}
private var func:Function;
function createDelegate(obj:Object):Function
{
return create(obj, func);
}
}
[/AS]
And to retrieve args past, see this simple class
[AS]
import mx.utils.Delegate;
class Foo {
private var __btn:MovieClip;
private var __name:String;
public function Foo(_b:MovieClip) {
__btn = _b;
init();
}
private function init() {
var myArgs:Array = ["one","two"];
//here I'm passing an array of items
__btn.onRelease = Delegate.create(this,clicker,myArgs);
}
private function clicker():Void {
//this is the hacky way to retrieve the args from arguments.caller
trace(arguments.caller.args);
}
}
[/AS]
Hope this may be of some use to someone.