消息事件总线

71 阅读1分钟

class EventEmitter {
    constructor() {
        this.eventBus = Object.create(null);
    }

    on(eventName, eventCallBack, thisArgs) {
        this.eventBus[eventName] = this.eventBus[eventName] || []
        this.eventBus[eventName].push({eventCallBack, thisArgs})
    }

    off(eventName, eventCallBack) {
        const handlers = this.eventBus[eventName];
        if (!handlers) return
        const newHandlers = [...handlers];
        for (let i = 0; i < newHandlers.length; i++) {
            let handlers = newHandlers[i];
            if (handlers.eventCallBack === eventCallBack) {
                const index = handlers.indexOf(handlers);
                handlers.splice(index, i)
            }
        }
        if (!this.eventBus[eventName].length) {
            delete this.eventBus[eventName]
        }
    }

    emit(eventName, ...payLoad) {
        const handlers = this.eventBus[eventName];
        if (!handlers) return
        handlers.forEach(handler => {
            handler.eventCallBack.apply(handler.thisArgs, payLoad)
        })
    }
}

const eventBus = new EventEmitter();

const handleCallback = function () {
    console.log("5555", this)
}
eventBus.on("abc", handleCallback, {name: "why"})


eventBus.emit("abc", 123)