前端待看

实现一个 EventEmitter

2017-06-13  本文已影响345人  waka

https://scriptoj.com/problems/36

class EventEmitter {

    constructor() {
        this.messageBox = {};
    }

    on(eventName, func) {
        const callbacks = this.messageBox[eventName] || [];
        callbacks.push(func);
        this.messageBox[eventName] = callbacks;
    }

    emit(eventName, ...args) {
        const callbacks = this.messageBox[eventName];
        if (callbacks.length > 0) {
            callbacks.forEach((callback) => {
                callback(...args);
            });
        }
    }

    off(eventName, func) {
        const callbacks = this.messageBox[eventName];
        const index = callbacks.indexOf(func);
        if (index !== -1) {
            callbacks.splice(index, 1);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读