egret 自定义事件

在游戏开发过程中,程序常常需要跨模块获取信息。跨模块传递信息的方法有多种,通过自定义事件来获取信息是一个方法。
可以了解一下:

/**
 * 自定义事件管理
 * 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));
	}
}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值