Return to Snippet

Revision: 24896
at March 15, 2010 11:03 by chrisaiv


Initial Code
-EventCentral.as-
package {

import flash.events.*;

    public class EventCentral extends EventDispatcher {
    private static var instance:EventCentral;
    public static function getInstance():EventCentral {
      if (instance == null){
         instance = new EventCentral(new SingletonBlocker());
      }
      return instance;
}
      public function EventCentral(blocker:SingletonBlocker):void{
        super();
        if (blocker == null) {
           throw new Error("Error: instantiation failed; Use EventCentral.getInstance()");
       }
}
        public override function dispatchEvent($event:Event):Boolean{
        return super.dispatchEvent($event);
}
}
}
internal class SingletonBlocker {}

--ProjectEvent.as--

package {
      import flash.events.Event
      public class ProjectEvent extends Event {
        public static const SOME_EVENT:String = "ProjectEvent.onSomeEvent";
        public var params:Object;
        public function ProjectEvent($type:String,$params:Object = null){
          super($type,true,true);
          this.params = $params;
}
       public override function clone():Event {
           return new ProjectEvent(this.type,this.params);
}
     override public function toString():String{
          return ("[Event ProjectEvent]");
}
}
}

To set up a listener:

EventCentral.getInstance().addEventListener('ProjectEvent.SOME_EVENT',handleSomeEvent);
function handleSomeEvent(event:ProjectEvent):void{
trace(event.params.param1);
}

to dispatch:

EventCentral.getInstance().dispatchEvent(new ProjectEvent('ProjectEvent.SOME_EVENT',{param1:'something'}));

Initial URL
http://blog.flexcommunity.net/?p=189

Initial Description
Simple, elegant solution that demands re-broadcast.  Author's explanation of the class: So I had the stage listen for the keyboward event, and when it heard it, dispatch it through this singlton instance, whcih the scroller can invoke as a listener, and viola, it worked perfectly! All events that need to travel all over the project, to parents, grandparents, and to all points in the display list, will now do so through this great EventCentral singleton.

Initial Title
AS3: Singleton Event Controller

Initial Tags

                                

Initial Language
ActionScript 3