I want the stage to react every time some changes are made to certain 开发者_运维问答objects. Is there a way to write custom Event? I could of course modify this object, but I would like to know if there is any more OOP
way to do it. And events ARE OOP
, ain't they?
A custom event class can be written like this:
public class MyEvent extends Event
{
private var evtData:Object;
public function MyEvent(type:String, data:Object)
{
super(type);
//fill this.evtData here
}
override public function clone():Event
{
return new MyEvent(type, evtData);
}
}
then dispatch this event by:
dispatch(new MyEvent("someName", obj))
and catch it like
myObj.addEventListener("someName", handleMyEvent);
function handleMyEvent(evt:MyEvent):void
{
//do something with evt
}
Lets say you have a property count
in some class. Easiest way is to generate setter and getter for this property and inside the setter to dispatch some custom event.
protected var _count:Number;
public function get count():Number
{
return _count;
}
public function set count(value:Number):void
{
_count = value;
dispatchEvent(new CountEvent(CountEvent.COUNT_CHANGED, value, true));
}
This is the custom event class:
public class CountEvent extends Event
{
public static const COUNT_CHANGED:String = "countChanged";
public var data:Object;
public function CountEvent(type:String, data:Object, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.data = data;
}
override public function clone():Event
{
return new CountEvent(type, data, bubbles, cancelable);
}
}
Note that if you need the value of the property and don't have reference to the object itself, you can create a data-object event. In order for this kind of custom event to work properly you need to override the clone method, which is used every time the event is re-dispatched.
If you are looking for more advanced way of "observing" something is by using some custom code, e.g. http://code.google.com/p/flit/source/browse/trunk/flit/src/obecto/utility/observe/Observe.as?r=190
In either way you must decide whether you want to modify your class by adding a dispatcher (if your class is not a EventDispatcher subclass) and dispatch an event or use some other techniques. Another way is to make the property [Bindable]
and use a binding between your property and some function to watch if something changes.
精彩评论