Laya 自制框架之事件管理器
Laya 自制框架之事件管理器
1 package framework.manager 2 { 3 import framework.event.FrameworkEvent; 4 5 import laya.events.EventDispatcher; 6 7 /** 8 * 编写事件管理器的目的是: 9 * 1.统筹全局事件的编写方案 10 * 2.统一管理事件派发 11 * 3.使用callater解决事件重复调用,事件阻塞 12 * 13 * --ixenos 2021年4月13日19点12分 14 */ 15 public class EventManager extends EventDispatcher 16 { 17 private static var _ins:EventManager; 18 19 private var _laterBuffer:Array; 20 21 public function EventManager() 22 { 23 _laterBuffer = []; 24 } 25 26 public static function get ins():EventManager{ 27 if(!_ins){ 28 _ins = new EventManager(); 29 } 30 return _ins; 31 } 32 33 public static function clean():void{ 34 if(_ins){ 35 _ins = null; 36 } 37 } 38 39 /** 40 * 派发事件 41 * @param type 42 * @param data 43 * 44 */ 45 public function dispatchLaterEvent(type:String):void{ 46 var lBuf:Array = EventManager.ins.laterBuffer; 47 if(!lBuf){ 48 lBuf = []; 49 EventManager.ins.laterBuffer = lBuf; 50 } 51 if(lBuf.indexOf(type)==-1){ 52 lBuf.push(type); 53 } 54 55 Laya.timer.callLater(EventManager.ins, EventManager.ins.flushLaterBuffer); 56 } 57 58 public function flushLaterBuffer():void{ 59 Laya.stage.event(FrameworkEvent.LATTER_EVENT, [EventManager.ins.laterBuffer]); 60 EventManager.ins.clearLaterBuffer(); 61 } 62 63 public function set laterBuffer(arr:Array):void{ 64 _laterBuffer = arr; 65 } 66 67 public function get laterBuffer():Array{ 68 if(!_laterBuffer){ 69 _laterBuffer = []; 70 } 71 return _laterBuffer; 72 } 73 74 public function clearLaterBuffer():void{ 75 laterBuffer = []; 76 } 77 78 /** 79 * 注册延迟调用事件 80 * @param type 81 * @param caller 82 * @param listener 83 * 84 */ 85 public function regLaterEvent(caller:*, listener:Function):void{ 86 regEvent(FrameworkEvent.LATTER_EVENT, caller, listener); 87 } 88 89 /** 90 * 注册全局事件 91 * @param type 92 * @param caller 93 * @param listener 94 * @param args 95 * 96 */ 97 public function regEvent(type:String, caller:*, listener:Function, args:Array=null):void{ 98 Laya.stage.on(type, caller, listener, args); 99 } 100 101 /** 102 * 销毁延迟调用事件 103 * @param type 104 * @param caller 105 * @param listener 106 * 107 */ 108 public function removeLaterEvent(caller:*, listener:Function):void{ 109 removeEvent(FrameworkEvent.LATTER_EVENT, caller, listener); 110 } 111 112 /** 113 * 销毁全局事件 114 * @param type 115 * @param caller 116 * @param listenter 117 * 118 */ 119 public function removeEvent(type:String, caller:*, listenter:Function):void{ 120 Laya.stage.off(type, caller, listenter); 121 } 122 123 } 124 }