unliar / unliar.github.io

一个已经不再使用的静态博客,新的博客在后边。
https://happysooner.com
0 stars 0 forks source link

实现一个发布订阅模式 #28

Open unliar opened 3 years ago

unliar commented 3 years ago
function EventEmitter() {
    this.listeners = {}
}

EventEmitter.prototype.on = function (e, cb) {
    const listeners = this.listeners
    const eArray = listeners[e]
    if (Array.isArray(eArray)) {
        !eArray.includes(cb) ? eArray.push(cb) : null
        return
    } else {
        listeners[e] = [cb]
    }

}

EventEmitter.prototype.emit = function (e) {
    const args = Array.from(arguments)
    args.shift()
    const ls = this.listeners[e]
    if (!e || !ls || ls.length == 0) return
    ls.forEach(cb => {
        cb(...args)
    })

}