How do I define my own events in AS3?
How do I define my own event listeners in AS3? I know it has to do with dispatch event, but I'm pretty much lost on how to use it.
I'm writing custo开发者_C百科m classes.
If you don't need to pass arguments with the events, just using a string like erkmene said will work.
The listener:
dispatchingObject.addEventListener( "SomeEvent", onEvent );
The dispatcher:
dispatchEvent( new Event( "SomeEvent" ) );
Make sure the class dispatching the event extends EventDispatcher either directly or somewhere in the class hierarchy.
The above code works but its best if the dispatching object holds the names of the events that it dispatches in static constant variables.
The listener:
dispatchingObject.addEventListener( DispatchingClass.SOME_EVENT, onEvent );
The dispatcher:
public static const SOME_EVENT : String = "SomeEvent";
dispatchEvent( new Event( SOME_EVENT ) );
You have to implement IEventDispatcher. Like this:
class ExampleDispatcher implements IEventDispatcher {
private var dispatcher:EventDispatcher;
public function ExampleDispatcher(){
dispatcher = new EventDispatcher(this);
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
dispatcher.addEventListener(type, listener, useCapture, priority);
}
public function dispatchEvent(evt:Event):Boolean {
return dispatcher.dispatchEvent(evt);
}
public function hasEventListener(type:String):Boolean {
return dispatcher.hasEventListener(type);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {
dispatcher.removeEventListener(type, listener, useCapture);
}
public function willTrigger(type:String):Boolean {
return dispatcher.willTrigger(type);
}
}
TECHNICALLY you can define these functions without the implement, but it just kinda makes it more organized.
In addition to Aurel300's answer; keep in mind that every DisplayObject (Sprite, MovieClip) is also an event dispatcher. You may dispatch an event by writing something like:
dispatchEvent(new Event('my_event'));
You may also create your custom event by extending the Event class. The event type ('my_event' above) is just a string to differentiate that specific event from all other events. For example when you write:
dispatchEvent(new Event(Event.COMPLETE));
you are just using the constant COMPLETE's string value. You may also get the same effect by writing:
dispatchEvent(new Event('complete'));
All the event listeners that listen that object for the 'complete' type of events will catch this.
精彩评论