DelegateHelper

Having done a lot of .Net programming over the past few years, I found myself really missing the .Net event/delegate pattern, particularly the ability to easily pass a reference to the object triggering the event, and an object containing arbitrary data (a la eventargs) into the scoped event handler. This became a lot more so when I started using Flash to build UIs for regular commercial software as opposed to websites.

So, I extended the Delegate class with this DelegateHelper to do just that more or less.

Here’s the class:

/**
 * @author = tcoz
 * Extends basic flash delegate functionality
 * so that you can pass reference to event thrower 
 * and any other arbitrary data as an object with props
 * to the indicated event handler
 */
  
class DelegateHelper extends mx.utils.Delegate
{        
private var func:Function;
    private var scope:Object;
    private var trigger:Object;
    private var data:Object;
    
    // obj = object with handler the handler function, f = that function, args = optional data
    public function DelegateHelper(obj:Object, f:Function, args:Object)
    {
        func = f;
        scope = obj;
        data = args;
    }
    
    // trig = object that is triggering the event, s = the function (i.e., "onPress")
    public function addToUser(trig:Object, s:String)
    {        
        trigger = trig;
        trig[s] = create(this, passTrigger);
    }
    
    private function passTrigger()
    {
        func.call(scope, trigger, data);
    }
}

//////////////////////////////////////////

And Here’s the use (remember to import DelegateHelper)

// instantiant in constructor or whatever
private var dataObject;

// create delegatehelper with desired scope and function reference
var delRelease:DelegateHelper = new DelegateHelper(this, onButtonRelease);
                
// subscribe to targetobject and targetobjects's desired event
delRelease.addToUser(targetObject, "onRelease");

...manipulate dataObject if needed, or get it from somewhere else, etc...

// event handler in subscribed scope, which receives a reference to the event thrower
// and an object with whatever data
private function onButtonRelease(sender:Object, data:Object):Void
{
    // reference to sender, and any other info, available!
}

I’ve fiddled with typing the DataObject (basically emulating the .Net EventArgs class) and a couple of other things, like destroying the helpers, but this is the basics of it. I’ve found it pretty useful in a couple of big projects, really lets me collapse a lot of code and implement some nice clean patterns. I’ll post an update when it’s ready if people seem interested. Not as far reaching as the efforts with compilers and whatnot to emulate this functionality, but lightweight, performant and easy to use.