Good ol' delegates in AS3 and Flex

In ActionScript there are several ways of communicating 2 classes.

Passing an instance or composition

This is probably the most obvious one. Pass an instance of one class to the other class, then you can call its public methods.

The good: You can call any public method on A and also access (and modify!) any of its public properties.
The bad: The type passed can only be A (although you can ease out this restriction using interfaces). Also this is a 1-to-1 process, if more than one object needs to get notified of the action, you have to code that yourself.

Using events

In this method class A is a listener of class B.

The good: 1-to-many communication. Different objects that might have nothing to do with each other can listen to the same event. Also class B doesn''t need to know anything about who's listening (therefore avoiding coupling).
The bad: You might run into memory leaks.You need to create one class per event. Well, this is not bad per se, it's just a little bit extra coding. Also remember that in AS3 your events should extend from the generic flash.events.Event.

Delegates

This is the one you don't see that often and the one I'd to comment. What we do here is passing a function to class B and class B executes it whenever it has to. See a sample in this simplified code:

[code lang="actionscript"]
class A{

function wadus(){
var b:B = new B(myHandler);
}

function myHandler(myParam:String){
trace("myHandler > " + myParam);
}

}

class B{

function B(callback:Function){
// do whatever here, even asynchronous stuff
callback("Hello world"); // now when you fancy execute the callback
}

}
[/code]

The good: Same as events, we avoid coupling because B doesn't know anything about A, just needs a function to call.
The bad: We lose strict data typing at compile time. Also this is a 1-to-1 method.

You can do this in Flex too, just check out how this class is setting up the "on" methods of this one. And how the later executes them when needed.

As I'm pretty new with AS3 and Flex I'm not sure what people think about this and possible side effects.

Back to index