eventEmitter的简单实现

class Emitter {
    constructor() {
        this.cb = {};
    }
    on(name, fn) {
        if (!this.cb[name]) {
            this.cb[name] = [fn];
        } else {
            this.cb[name].push(fn);
        }
    }
    emit(name, ...args) {
        this.cb[name].forEach(fn => fn.call(this, ...args));
    }
    remove(name, fn) {
        let index = this.cb[name].indexOf(fn);
        if (index !== -1) {
            this.cb[name].splice(index, 1);
        }
    }
    once(name, fn) {
        // 调用一次的实现,封装传入函数,一次调用后remove
        function onceFn(...args) {
            fn.call(this, ...args);
            this.remove(name, onceFn);
        }
        this.on(name, onceFn);
    }
}

// 测试代码
let emitter = new Emitter();
let test = function (value) {
    console.log('test' + value);
};
let test_again = function () {
    console.log('again');
};
emitter.on('test', test);
emitter.on('test', test_again);
emitter.emit('test', 123);

// emitter.once('once', test);
// emitter.emit('once', 123);
// emitter.emit('once', 456);
原文地址:https://www.cnblogs.com/chh1995/p/14944248.html