在游戏开发过程中,程序常常需要跨模块获取信息。跨模块传递信息的方法有多种,通过自定义事件来获取信息是一个方法。
可以了解一下:
/**
* 自定义事件管理
* 2019.7.9
*/
class CustomEventMgr{
//事件广播器
private _dispatcher:egret.EventDispatcher;
private constructor() {
this._dispatcher = new egret.EventDispatcher();
}
private static _ins:CustomEventMgr;
public static ins():CustomEventMgr
{
if(CustomEventMgr._ins == null)
CustomEventMgr._ins = new CustomEventMgr();
return CustomEventMgr._ins;
}
/**触发事件 */
public static dispatcherEvent(e:egret.Event):void
{
CustomEventMgr.ins()._dispatcher.dispatchEvent(e);
}
/**添加事件 */
public static addEvent(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number):void
{
CustomEventMgr.ins()._dispatcher.addEventListener(type,listener,thisObject,useCapture,priority);
}
/**移除事件 */
public static removeEvent(type: string, listener: Function, thisObject: any, useCapture?: boolean):void
{
CustomEventMgr.ins()._dispatcher.removeEventListener(type,listener,thisObject,useCapture);
}
}
class EventTest{
constructor()
{
this.test();
}
test() {
//注册监听
let name = "TestEvent";
CustomEventMgr.addEvent(name, (e: egret.Event) => {
console.log("TestEvent:", e);
console.log("TestEvent:",e.data);
},this);
}
//触发事件
dispatchEventTest(): void {
let data = "aaa";
CustomEventMgr.dispatcherEvent(new egret.Event("TestEvent",false,false,data));
}
}
结果