欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 【cocos creator】【ts】事件派发系统

【cocos creator】【ts】事件派发系统

2025/5/4 17:20:29 来源:https://blog.csdn.net/K86338236/article/details/145101664  浏览:    关键词:【cocos creator】【ts】事件派发系统

触发使用:
EventTool.emit(“onClick”)
需要监听的地方,onload调用:
EventTool.on(“onClick”, this.onClickEvent, this)


/**事件派发*/class EventTool {protected static _instance: EventTool = null;public static get Instance(): EventTool {if (EventTool._instance == null) {EventTool._instance = new EventTool();}return EventTool._instance;}isValidNode(node) {return node && node.isValid;}/**添加事件监听  * @param {string} event 事件名  * @param {Function} handler 事件响应函数  * @param {object} scope 函数所在的对象*/on(event: any, handler: Function, scope: any) {if (typeof handler != "function") {console.error("没有事件响应函数!", event);return;}let id = scope.uuid || scope.__custom_id__;if (!id) {scope.__custom_id__ = "" + Date.now() + Math.random();id = scope.__custom_id__;}this[id] = this[id] == undefined ? [] : this[id];if (Array.isArray(this[id])) {this[id].push(event);} else {console.error("有一个跟当前脚本同名的事件!");return;}this[event] = this[event] ? this[event] : {};this[event][id] = { handler: handler, scope: scope, times: cc.macro.REPEAT_FOREVER };}onOnce(event, handler, scope) {this.on(event, handler, scope)let id = scope.uuid || scope.__custom_id__;this[event][id].times = 1}/*** 移除事件监听* @param scope * @param event event 为空则移除scope所有监听*/off(scope?: any, event?: any) {let id = scope.uuid || scope.__custom_id__;if (!id) {return;}if (event) {this[event] = this[event] ? this[event] : {};this[event][id] = null;delete this[event][id];return;}let events = this[id];if (Array.isArray(events)) {for (let i = 0; i < events.length; i++) {this[events[i]][id] = null;delete this[events[i]][id];}}this[id] = [];delete this[id];}/**发送事件  * 参数个数不限,第一个参数为事件名,其余为传递给响应函数的参数  * @param {string} event 事件名    * @param args {}传递给响应函数的参数集,可以为空 */emit<T>(event, ...args) {let onwers = this[event];// console.log("trigger event:" + event);if (onwers) {for (let key in onwers) {let data = onwers[key];if (--data.times <= 0) {delete onwers[key];}try {if (!data.scope || !data.scope.node || !data.handler) continue;data.handler.apply(data.scope, args);} catch (e) {// console.error(e)}}} else {// console.log(event + "事件还没有添加事件监听!");}}
};
export default EventTool.Instance

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词