js实现简单的中央事件总线EventBus

347 阅读1分钟

js实现简单的中央事件总线EventBus

在vue中会用到中央事件总线进行小型项目的组件通信,这里用js简单实现一个,学习记录,有不足之处可指出

class EventBus {
  constructor() {
    this.eventList = new Map() // 注册事件收集器
  }
  // 注册事件
  on(name,fn) {
    this.eventList.set(name,fn)
  }
  // 触发事件
  emit(eName, data) {
    const cb = this.eventList.get(eName)
    if(cb) {
      cb(data)
    } else{
      throw new Error('no Registration event')
    }
  }
  // 移除事件
  remove(eName) {
    this.eventList.delete(eName)
  }
}
const a = new EventBus()
a.on('handleKeyword',(value)=> {
  console.log('接收到handleKeyword:', value)
})
a.on('suc',(value)=> {
  console.log('接收到suc:', value)
})

a.emit('handleKeyword', 'hello') //接收到handleKeyword: hello
a.emit('suc', 'suchello') // 接收到suc: suchello
a.emit('suc', 'suchello11') // 接收到suc: suchello11
// a.emit('suc111', '传递的数据suc') // 没有注册的事件 报错 no Registration event
a.remove('suc') // 移除事件

// 没有注册的事件 报错 no Registration event
a.emit('suc', 'suchello')