views:

47

answers:

1

I'm trying to setup something like Aspect Oriented Programming in Actionscript 3, basically the only thing I need to be able to do is something like this:

SomeClass.getMethod("methodName").addEventListener(afterMethodExecuted, function() {
    //run code
});

This way I can run code after (or before) any method in any class has run, allowing numerous new possibilities.

How should I implement this?

+2  A: 

You can write a wrapper on a method. The BindUtils class of the Flex library does just that using the ChangeWatcher. It does so by wrapping a property but in ActionScript a method is just a property.

I suggest reading the code for those methods ($FLEX_ROOT/sdks/4.0.0/frameworks/projects/framework/src/) to get an idea of how you can do the same.

You might also be interested in the FunctionReturnWatcher.

James Fassett
Note that the given method should be updated for all instances if I give a class rather than an object (class instance). Do the classes you linked work like that?
Tom
As far as I can tell the classes I linked will not do that. You can probably wrap the class constructor in a similar method to ensure that each instance it creates is wrapped. (I hope that makes sense - have a look here http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/Object.html#constructor to see how to overwrite the constructor of an Object)
James Fassett
This will probably cause a significant loss of performance though.
Tom
I'm not sure what you mean by performance loss. Each instance will have to call one extra function when it is instantiated, so I guess you'll be paying for a stack-frame. That should be the only issue since Flash already does dynamic dispatch on all function calls (AFAIK)
James Fassett