Recently I’ve read posts about the speed advantages of callbacks over events on the blogs of Troy Gilbert and Jackson Dustan. But instead of using a strategy like stated in the comment here we use something which we call CallbackCommand and relies to the command pattern. It’s some kind of proxy command to call methods not being part of the command itself.
If you adapt the source of the above mentioned comment and transform it in something like this you don’t have to give a link of the instance holding the method to be called into another. (I’m afraid this will lead to carbage collection issues?)
class MyAPILoader
{
private var _loadCommand: ICommand;
private var _dispObj: DisplayObject;
public function MyAPILoader(url:String, loadCommand:ICommand)
{
_loadCommand = loadCommand;
// initiate the load...
}
private function onLoaded(dispObj:DisplayObject): void
{
_dispObj = dispObj;
_loadCommand.execute();
}
public function get displayObject(): DisplayObject
{
return _dispObj;
}
}
The code of the CommandCallback looks like this:
package rg.command
{
import rg.interfaces.ICommand;
public class CallbackCommand implements ICommand {
private var _func:Function;
private var _args:Array;
public function CallbackCommand(func:Function,...args) {
_func = func;
_args = args;
}
override public function execute() : void {
_func.apply(this,_args);
}
}
}
Finally you settle everything like that:
var loader: MyAPILoader = new MyApiLoader("http://...", new CallbackCommand(loaded, additionalParams));
private function loaded(additionalParams: Type): void
{
addChild(loader.displayObject);
}
Instead of calling simple methods by Callback Commands you get the option to use “real” commands instead additionally. I haven’t checked the performance losses against direct callbacks yet but it shouldn’t be that much slower.