javascript 实现一个简单的EventEmitter

实现一个EventEmitter,主要是事件的绑定on和发送emit。
相同的事件名是会被分别触发的。

function EventEmitter() {
    //listeners是一个对象,key对应的是event,value对应的是函数的数组。
    this.listeners = {}
}

EventEmitter.prototype.on = function(event, func) {
    try {
        //function加入数组
        this.listeners[event].push(func)
    } catch (error) {
        //如果listeners不是数组,则定义数组,并把第一个function加入
        this.listeners[event] = [func]
    }
}

EventEmitter.prototype.emit = function(event, ...args) {
    if (this.listeners[event]) {
        this.listeners[event].forEach(func => {
            // func.apply(null, args)
            func(...args)
        });
    }
}


const ee = new EventEmitter()
ee.on('some_event', (...args) => {
    console.log('some event shift', ...args)
})
ee.on('some_event', (...args) => {
    console.log('some event shift222', ...args)
})
ee.emit('some_event', 'abc', '123')