Written by Cody Snider
Saturday, December 6th, 2008
When you’re faced with the task of firing events from within a class and you can’t extend EventDispatcher, you need to implement the IEventDispatcher interface. It’s a straightforward approach to keeping your classes loosely coupled, well-encapsulated and capable of firing their own events:
View Code ACTIONSCRIPT
class YourClass implements IEventDispatcher { private var eventDispatcher:EventDispatcher = new EventDispatcher(); public function YourClass() { // do constructor stuff here } 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 removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void { eventDispatcher.removeEventListener(type, listener, useCapture); } public function dispatchEvent(event:Event):Boolean { return eventDispatcher.dispatchEvent(event); } public function hasEventListener(type:String):Boolean { return eventDispatcher.hasEventListener(type); } public function willTrigger(type:String):Boolean { return eventDispatcher.willTrigger(type); } }
All we’re really doing here is creating a private EventDispatcher object and hooking all its methods through public methods of your custom class.