cocos creator从零开发简单框架(22)-事件管理器

事件管理器一般用于各模块代码之间的解耦,提高代码的可维护性。

新建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)
                }
            }
        })
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!