事件管理器一般用于各模块代码之间的解耦,提高代码的可维护性。
新建framework/scripts/manager/EventMgr.ts
,内容如下 。
interface IHandler {
cb: Function
ctx: any
}
export default class EventMgr {
private static _events: Map<string, IHandler[]> = new Map()
public static on(event: string, cb: Function, ctx?: any) {
if (this._events.has(event)) {
this._events.get(event).push({ cb, ctx })
} else {
this._events.set(event, [{ cb, ctx }])
}
}
public static off(event: string, cb: Function, ctx?: any) {
if (!this._events.has(event)) {
console.error('EventMgr.off event:' + event + ' 未注册')
return
}
const index = this._events.get(event).findIndex(i => cb === i.cb && i.ctx === ctx)
index >= 0 && this._events.get(event).splice(index, 1)
}
public static emit(event: string, ...params: any[]) {
if (!this._events.has(event)) {
console.error('EventMgr.emit event:' + event + ' 未注册')
return
}
this._events.get(event).forEach(({ cb, ctx }) => {
cb.apply(ctx, params)
})
}
public static clear(ctx: any): void {
if (!ctx) return
this._events.forEach((handlers, _event) => {
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i].ctx == ctx) {
handlers.splice(i, 1)
}
}
})
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。