Listen to any change in the values of an Object in Actionscript
I have an Object in actionscript which has a few dozens of properties each of which is defined to be bindable and has its own change event. I would like to listen to any changes made to this object without having to add a listener to all of its properties. Is there a way in actionscript using which I can listen to any change in the values of an开发者_开发问答 Object ?
Thanks, -A
You can use the PropertyChangeEvent on a [Bindable] class to listen for any property changes. As long as you're using the get/set properties.
package
{
[Bindable]
public class Person
{
private var _firstName:String;
private var _lastName:String;
private var _age:Number;
public function get firstName():String
{
return _firstName;
}
public function set firstName(value:String):void
{
_firstName = value;
}
public function get lastName():String
{
return _lastName;
}
public function set lastName(value:String):void
{
_lastName = value;
}
public function get age():Number
{
return _age;
}
public function set age(value:Number):void
{
age = value;
}
public function Person()
{
// empty constructor
}
}
}
Then, in your using class add the event listener.
public var p:Person;
private function addListener():void
{
p = new Person();
p.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onPropertyChange);
}
private function onPropertyChange(event:PropertyChangeEvent):void
{
trace(event.property + " " + event.kind + " " + event.oldValue + " " + event.newValue);
}
I don't think there is a way to listen to listen to an event without adding a listener. However, there is no reason you can't use the same listener function for ever event change. Adding the event listeners should be relatively trivial:
myObject.addEventListener('property1Changed',myChangeHandler) myObject.addEventListener('property2Changed',myChangeHandler)
etc... etc..
You could also have each property fire a generic change event in addition to the property specific change event. Although tedious, this should be an quick cut and paste job.
One way could be to call an objectChanged() function on each setter.
public function set property1(arg) : void{
property1 = arg;
objectChanged();
}
Edit: You could make the class implement IPropertyChangeNotifier
精彩评论