Dispatching an event — custom style
Let’s say you just wrote a great AS3 class that extends something non-UI. Now when you’re done you want to dispatch an event but you don’t inherit “dispatchEvent” since you’re outside of UI classes (which inherit the event dispatcher).
This one has plagued me. In fact there are so many classes in my projects which shouldn’t be extending anything but I ended up extending UIComponent just to get the event dispatcher. Well, I’m here to learn you up on not having to do this hack.
import flash.display.Sprite;
import flash.events.Event;
public class MyDispatcher extends Sprite {
public function MyDispatcher() {
var dispatcher:CustomDispatcher = new CustomDispatcher();
dispatcher.addEventListener(“customEvent”, handleEvent);
dispatcher.dispatchEvent(new Event(“customEvent”));
}
private function handleEvent(event:Event):void {
trace(event.type); // “customEvent”
}
}
}
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
class CustomDispatcher implements IEventDispatcher {
private var eventDispatcher:EventDispatcher;
public function CustomDispatcher() {
eventDispatcher = new EventDispatcher(this);
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public function dispatchEvent(event:Event):Boolean {
return eventDispatcher.dispatchEvent(event);
}
public function hasEventListener(type:String):Boolean {
return eventDispatcher.hasEventListener(type);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {
eventDispatcher.removeEventListener(type, listener, useCapture);
}
public function willTrigger(type:String):Boolean {
return eventDispatcher.willTrigger(type);
}
}
from http://www.kirupa.com/forum/showthread.php?p=1899603#post1899603
Leave a Reply