美文网首页
使用JavaScript手写一个事件总线功能

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

作者: Fairy_妍 | 来源:发表于2021-08-27 14:41 被阅读0次

    事件总线

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

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

    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已经实现了相应接⼝

    相关文章

      网友评论

          本文标题:使用JavaScript手写一个事件总线功能

          本文链接:https://www.haomeiwen.com/subject/kwyuiltx.html