Monday, July 12, 2010

Global Dispatcher

The purpose of this post is to use a dispatcher class to handle events between all content movies in a project.

For example, in movie A, you want to notify an event to movie B and movie C, instead of using movieA.addEventListener(movieAEvent) in movie B and movie C, now we only need to use simple below code in movie A:

var dispatcher: Dispatcher = new Dispatcher();
dispatcher.dispatchEvent(movieAEvent);


and in movie B and movie C, we use:

var dispatcher: Dispatcher = new Dispatcher();
dispatcher.addEventListener(movieAEvent, eventHandler);


The Dispatcher class can also use for communication between any objects with any instances or the stage. Very simple and useful.

package com.binhdocco.dispatcher {
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    
    /**
     * ...
     @author binhdocco

     */
    public class Dispatcher implements IEventDispatcher {
        
        protected static var disp: EventDispatcher;
        
        public function Dispatcher() {            
            if (disp == null)
                disp = new EventDispatcher();
        }
        
        /* INTERFACE flash.events.IEventDispatcher */
        
        public function addEventListener(type:String, listener:Function, 
                                        useCapture:Boolean = false, priority:int = 0
                                        useWeakReference:Boolean = false):void{
            disp.addEventListener(type, listener, useCapture, priority, useWeakReference);
        }
        
        public function dispatchEvent(event:Event):Boolean {            
            return disp.dispatchEvent(event);
        }
        
        public function hasEventListener(type:String):Boolean{
            return disp.hasEventListener(type);
        }
        
        public function removeEventListener(type:String, listener:Function, 
                                            useCapture:Boolean = false):void{
            disp.removeEventListener(type, listener, useCapture);
        }
        
        public function willTrigger(type:String):Boolean{
            return disp.willTrigger(type);
        }
        
    }

}

No comments: