SOURCE

function EventBus(){
    this.listener = []
}

EventBus.prototype.on = function(event,cb){
    if(!this.listener[event]){
        this.listener[event] = []
    }
    this.listener[event].push(cb)
}

EventBus.prototype.emit = function (event, ...param){
    this.listener[event].forEach((item) => {
        item(...param)
    })
}

EventBus.prototype.off = function(event, cb){
    for(let i = 0;i < this.listener[event].length;++i){
        if(cb === this.listener[event][i]){
            this.listener[event].splice(i,1)
            break // 一次之删除一个事件
        }
    }
}

const bus = new EventBus();
const callback = function(arr) {
    const sum = arr.reduce((sum, curr) => sum + curr);
    console.log(`Sum: ${sum}`);
}


bus.on('sum', callback);
bus.on('sum', callback);
bus.emit('sum', [1, 2, 3, 4, 5]);


bus.off('sum', callback);
bus.emit('sum', [1, 2, 3, 4]);

bus.off('sum', callback);
bus.emit('sum', [1, 2, 3, 4]);
console 命令行工具 X clear

                    
>
console