import Singleton from '../Base/SingLeton';
interface IItem {
func: Function;
ctx: unknown;
}
/***
* 事件中心管理类(本质就是一张map,key是事件名称,value是对应事件的函数列表)
* 存储事件名称,和函数列表
*/
export default class EventManager extends Singleton {
static get Instance() {
return super.GetInstance<EventManager>();
}
eventDic: Map<string, Array<IItem>> = new Map();
//第二个数组里面存的对象。
on(event: string, func: Function, ctx?: unknown) { //ctx:上下文 传上下文进去
if (this.eventDic.has(event)) {
this.eventDic.get(event).push({ func, ctx });
} else {
this.eventDic.set(event, [{ func, ctx }]);
}
}
off(event: string, func: Function) {
if (this.eventDic.has(event)) {
const index = this.eventDic.get(event).findIndex(i => func === i.func); //拿到对应事件的索引
index > -1 && this.eventDic.get(event).splice(index, 1);
}
}
emit(event: string, ...params: unknown[]) {
if (this.eventDic.has(event)) {
this.eventDic.get(event).forEach(({ func, ctx }) => {
ctx ? func.apply(ctx, params) : func(...params); //触发函数
});
}
}
clear() {
this.eventDic.clear();
}
}
事件中心-cocos
最新推荐文章于 2024-07-01 13:31:56 发布