SOURCE

class Event {
    _handlers = {} // 事件容器,用来装事件数组(因为订阅者可以是多个)

    // 注册事件
    on(type, handler) {
        this._handlers[type] = this._handlers[type] || []
        this._handlers[type].push(handler)
    }

    // 派发事件
    emit(type, ...params) {
        if (!this._handlers[type]) throw new Error("emit: 无效事件")
        this._handlers[type].forEach((handler) => handler(...params))
    }

    // 删除事件
    off(type, handler) {
        if (!this._handlers[type]) throw new Error("off: 无效事件")
        if (!handler) delete this._handlers[type]
        else {
            const idx = this._handlers[type].indexOf(handler)
            if (idx === -1) throw new Error("off: 无该绑定事件")
            this._handlers[type].splice(idx, 1)
            if (this._handlers[type].length === 0) delete this._handlers[type]
        }
    }
}


const event = new Event()
const qy1 = (a, b, c, d) => {
    console.log('qy1 ', a, b, c, d)
}
const qy2 = (a, b, c, d) => {
    console.log('qy2 ', a, b, c, d)
}

try {
    event.on('qy', qy1)
    event.on('qy', qy2)
    // event.off('qy')
    event.off('qy', qy1)
    // event.off('qy', qy2)
    event.emit('qy', 1, 2, 3, 4)
} catch (err) {
    console.log(err.message)
}
console 命令行工具 X clear

                    
>
console