AS3: Singleton Event Controller


/ Published in: ActionScript 3
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. -EventCentral.as-
  2. package {
  3.  
  4. import flash.events.*;
  5.  
  6. public class EventCentral extends EventDispatcher {
  7. private static var instance:EventCentral;
  8. public static function getInstance():EventCentral {
  9. if (instance == null){
  10. instance = new EventCentral(new SingletonBlocker());
  11. }
  12. return instance;
  13. }
  14. public function EventCentral(blocker:SingletonBlocker):void{
  15. super();
  16. if (blocker == null) {
  17. throw new Error("Error: instantiation failed; Use EventCentral.getInstance()");
  18. }
  19. }
  20. public override function dispatchEvent($event:Event):Boolean{
  21. return super.dispatchEvent($event);
  22. }
  23. }
  24. }
  25. internal class SingletonBlocker {}
  26.  
  27. --ProjectEvent.as--
  28.  
  29. package {
  30. import flash.events.Event
  31. public class ProjectEvent extends Event {
  32. public static const SOME_EVENT:String = "ProjectEvent.onSomeEvent";
  33. public var params:Object;
  34. public function ProjectEvent($type:String,$params:Object = null){
  35. super($type,true,true);
  36. this.params = $params;
  37. }
  38. public override function clone():Event {
  39. return new ProjectEvent(this.type,this.params);
  40. }
  41. override public function toString():String{
  42. return ("[Event ProjectEvent]");
  43. }
  44. }
  45. }
  46.  
  47. To set up a listener:
  48.  
  49. EventCentral.getInstance().addEventListener('ProjectEvent.SOME_EVENT',handleSomeEvent);
  50. function handleSomeEvent(event:ProjectEvent):void{
  51. trace(event.params.param1);
  52. }
  53.  
  54. to dispatch:
  55.  
  56. EventCentral.getInstance().dispatchEvent(new ProjectEvent('ProjectEvent.SOME_EVENT',{param1:'something'}));

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.