带有handleEvent的eventEmitter

class EventEmitter {
    #listeners = Object.create(null);
    #maxListener = 10;

    constructor() {
        
    }

    on(evt, cb) {
        const cbs = this.#listeners[evt] || (this.#listeners[evt] = []);
        cbs.length < this.#maxListener && (typeof cb == 'function' || cb.hasOwnProperty('handleEvent')) && cbs.push(cb);
    }

    once(evt, cb) {
        const fn = (...args) => {
            cb.call(null, ...args);
            this.off(evt, fn);
        };
        this.on(evt, fn);
    }

    off(evt) {
        (evt && this.#listeners[evt]) ? this.#listeners[evt] = [] : this.#listeners = Object.create(null);
    }

    emit(evt, ...args) {
        if (!this.#listeners[evt]) return
        this.#listeners[evt].forEach(cb => {
            if (cb.hasOwnProperty('handleEvent')) {
                cb['handleEvent'].call(cb, ...args);
            } else {
                cb.call(null, ...args);
            }
        });
    }
}
posted @ 2021-03-13 14:02  风的线条昵称已被使用  阅读(56)  评论(0编辑  收藏  举报