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);

 

eventEmitter的简单实现

上一篇:如何查看图像文件元标签信息


下一篇:vue、vue-antd 动态表格,table某一列两个input