手写EventBus

155 阅读1分钟

我们可以通过event的发布和订阅着手

class EventBus {
    constructor () {
        this.events = this.events || {}
    }
}

EventBus.prototype.broadcast = (type, ...args) => {
    const events = this.events[type] || []
    if (Array.isArray(events) && events.length) {
        events.map(event => event(...args))
    }
}

EventsBus.prototype.subscribe = (type, fn) => {
    const events = this.events[type]
    if (!events) this.events[type] = []
    this.events[type].push(fn)
}

订阅就是把所有类型的方法收集起来,按类型分类,如下:

this.events = {
    cat: [fn1, fn2, ...],
    dog: [fn1, fn2, ...]
}

广播,就是找到对应类型的事件列表,然后一次执行