使用JavaScript手写一个事件总线功能

2021-08-27  本文已影响0人  Fairy_妍

事件总线

事件总线主要是实现一些任意的或非父子关系的组件之间的数据通信

实现一个事件总线功能需要:

  1. 事件派发 $emit
  2. 监听 $on
  3. 回调管理
// Bus:事件派发、监听和回调管理
class Bus {
  constructor(){
    this.callbacks = {}
  }
  $on(name, fn){
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
  }
  $emit(name, args){
    if(this.callbacks[name]){
      this.callbacks[name].forEach(cb => cb(args))
    }
  }
}
// main.js
Vue.prototype.$bus = new Bus()
// child1:监听child2中的事件及传值
this.$bus.$on('event-from-child2', msg => {
  console.log('Child1:', msg);
});
// child2:派发事件
this.$bus.$emit('event-from-child2', 'some msg from child2')

实践中通常⽤Vue代替Bus,因为Vue已经实现了相应接⼝

上一篇下一篇

猜你喜欢

热点阅读