views:

261

answers:

2

When developing in ActionScript 3, I often find myself looking for a way to achieve something similar to what is offered by python's __getattr__ / __setattr__ magic methods i.e. to be able to intercept attribute lookup on an instance, and do something custom.

Is there some acceptable way to achieve this in ActionScript 3? In AS3 attribute lookup behaves a little differently for normal (sealed) and dynamic classes -- ideally this would work in the same way for both cases. In python this works beautifully for all kinds of objects (of course!) even for subclasses of dict itself!

A: 

Look a the flash.utils.Proxy object.

The Proxy class lets you override the default behavior of ActionScript operations (such as retrieving and modifying properties) on an object.

OXMO456
I tend to forget about flash.utils.Proxy -- because you can only use it by extending it. This is overly constraining... given that AS3 does not support multiple inheritance, it makes it impossible to use Proxy -- when extending any other type -- for override the GetProperty/setProperty behaviour.
Mario Ruggier
A: 

in as3 you can code explicit variables' accessors. ex Class1:

private var __myvar:String;

public function get myvar():String { return __myvar; } public function set myvar(value:String):void { __myvar = value; }

now as you create an instance of Class1 you can access __myvar through the accessor functions. if you want to set bindable that var you have to put the [Bindable] keyword upon one of its accessors. further, you can also implement the getter or the setter only, so your var will be read or write only. i hope it helps ;)

pigiuz

pigiuz
But what if a priori you do not know what the properties you need are? I.e. dynamic objects e.g. Object, Dictionary? import flash.utils.Dictionary; var d:Dictionary = new Dictionary; d["abc"] = 123; // how to intercept this set property? trace(d["abc"]); // how to intercept this get property?All while still not losing the real nature of the base object i.e. if a Dictionary (or subclass thereof) it should continue to behave like one i.e. can still do whatever you can be done with a Dictionary e.g. to loop over the keys: for (var key:Object in d) { trace(key, d[key]); }
Mario Ruggier
in as3 that's not possible unless you write accessors for each property (or you take the proxy object way).a dirty workaround could be write a wrapper class for each basic data type, something like MyInterceptorArray or MyInterceptorDictionary where you simply wrap a private array, dictionary or whatever giving access to it through your handcrafted accessors. There's a cool lib (http://code.google.com/p/as3ds) here which implements datastructures that way.as3 is not a pythonic language, it's much more similar to java coding, and dynamic objects are mostly a bad programming way.
pigiuz