本篇文章小编给大家分享一下CocosCreator消息分发机制代码示例解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
具体方案
先定义监听回调类型
/** * 消息监听回调方法 */ export type NotifyListener = (src: any, data: any) => void;
通过key-value方式保存监听队列
private static msg2listDict: Dictionary< string, Array> = new Dictionary< string, Array >();
接口定义
/** * 添加多次监听者,需要手动移除 * @param msg * @param listener * @param target */ public static addListener(msg: string, listener: NotifyListener, target?: any): void {} /** * 添加单次监听者,事件触发后即移除 * @param msg * @param listener * @param target */ public static addOnceListener(msg: string, listener: NotifyListener, target?: any): void {} /** * 移除指定消息指定的监听者 * @param msg * @param listener */ public static removeMsgListener(msg: string, listener: NotifyListener): void {} /** * 移除指定消息所有监听者 * @param msg */ public static removeMsgAllListeners(msg: string): void {} /** * 移除指定目标对指定消息的监听 * @param msg * @param target */ public static removeTargetMsgListen(msg: string, target: any): void {} /** * 移除指定目标所有消息监听 * @param target */ public static removeTargetAllMsgListen(target: any): void {} /** * 派发消息 * @param msg * @param src * @param data */ public static notify(msg: string, src: any, data: any): void {}
在添加移除实现中,需要注意某消息可能正在派发。
对于一个消息新添加的监听者,应该在当前队列消息派发完后再派发,因此,添加一个待添加队列
private static listener2add: Array= [];
在添加监听者时做以下判断
// 该消息正在派发,放入待添加队列 if (NotifyCenter.notifyMsgs.indexOf(msg) >= 0) { NotifyCenter.listener2add.push(info); return; }
同样在移除监听者时,可能正在派发消息,避免对队列的修改导致for循环异常,添加一个待移除队列,派发消息时,如果该监听者在移除队列则不派发。在消息派发完后再将其移出队列
private static listener2remove: Array= [];
在移除监听者时做以下判断
// 该消息正在派发,放入待移除队列 if (NotifyCenter.notifyMsgs.indexOf(msg) >= 0) { NotifyCenter.listener2remove.push(list[i]); } else { list.splice(i, 1); }
派发消息时遍历指定消息下的队列
// 队列不存在,不需要处理 let list = NotifyCenter.msg2listDict.get(msg); if (!list) { return; } // 标记消息正在派发,多个消息可能同时在派发,同一消息可能标记多次 NotifyCenter.notifyMsgs.push(msg); // 处理消息派发 for (let i = 0, n = list.length; i < n; i++) { NotifyCenter._dispatch(list[i], src, data, false); }
派发消息时先判断是否在移除队列
// 在移除队列,不派发 if (NotifyCenter.listener2remove.indexOf(info) >= 0) { return; }
当前队列派发完后检查待添加队列
// 处理待添加队列派发 for (let i = 0, n = msg2add.length; i < n; i++) { if (listener2add[i].msg == msg) { NotifyCenter._dispatch(listener2add[i], src, data, true); } }
引入消息分发中心,隔离的系统、模块间通过消息监听和派发通信,避免互相引用耦合。
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔