Reputation: 13476
I have a dynamic Class
and what I would like to do is call a method everytime a property is appended to the class during run-time.
For example:
dynamic class Example
{
public function Example()
{
trace("New instance created");
}
public function setter(name:String, value:String):Void
{
trace("Property '"+name+"' created with value '"+value+"'");
}
}
And then from the timeline when I would add a new property to Example:
Example.newProperty = "some value";
I want it to trace:
Property 'newProperty' created with value ' some value'
I am fully aware that this is capable by using a function to set properties like so:
public function setter(name:String, value:String):Void
{
this[name] = "some value";
trace("Property '"+name+"' created with value '"+value+"'");
}
and calling it like so:
Example.setter("newProperty", "some value");
However I want this method to fire automatically when a property is added via the regular .dot
operator and not have to call a function explicitly.
Is this possible?
Upvotes: 3
Views: 477
Reputation: 39466
Could use Proxy
here.
Example class:
package
{
import flash.utils.Proxy;
import flash.utils.flash_proxy;
dynamic public class Example extends Proxy
{
private var _properties:Object = {};
override flash_proxy function setProperty(name:*, value:*):void
{
_properties[name] = value;
trace("Property '" + name + "' created with value '" + value + "'");
}
override flash_proxy function getProperty(name:*):*
{
return _properties[name];
}
}
}
Demo code:
var ex:Example = new Example();
ex.something = 10;
ex.more = "something more";
trace(ex.something);
trace(ex.more);
Output:
Property 'something' created with value '10'
Property 'more' created with value 'something more'
10
something more
Upvotes: 0
Reputation:
Since it's AS2, then, yes, your class has to implement __resolve(x)
method. I would, however, consider it a very questionable design decision. The function that accepts the key and the value looks much better to me, and, in the end, it's less code.
Upvotes: 1