手写EventBus

270 阅读1分钟

使用无序数据结构(字典,即对象)存储事件,方便迅速查找。

使用有序数据结构(队列,即数组)存储事件回调,遵循先进先出原则,先绑定的事件先触发。

class EventBus{
  constructor(){
    this._cache = {}
  }

  on(type,callback){
    this._cache[type] = this._cache[type] || []
    this._cache[type].push(callback)
  }

  off(type,callback){
    const fns = this._cache[type]
    if(!Array.isArray(fns)){
      return
    }

    if(!callback){
      fns.length = 0
      return
    }

    while(fns.indexOf(callback) !== -1){
      fns.splice(fns.indexOf(callback),1)
    }
  }

  emit(type,data){
    const fns = this._cache[type]
    if(!Array.isArray(fns)){
      return
    }

    fns.forEach(item => {
      item(data)
    })
  }
}

const bus = new EventBus()

function cyCallback1(res){
  console.log('cy on1: ',res)
}

function cyCallback2(res){
  console.log('cy on2: ',res)
}

bus.on('cy',cyCallback1)
bus.on('cy',cyCallback1)

bus.on('cy',cyCallback2)

bus.off('cy',cyCallback1)

bus.emit('cy','cy emit')