模拟实现vue的发布订阅模式

416 阅读1分钟

发布/订阅模式

发布订阅模式可分以下几个部分

  • 订阅者
  • 发布者
  • 信号中心 什么叫发布定义模式?

我们假定,存在一个“信号中心”,某个任务执行完了,就向信号中心“发布”(publish)一个信号,其他任务可以向信号中心“订阅”(subscribe)这个信号,从而知道什么时候自己可以开始执行了。这就叫做“发布订阅者模式”(publish-subscribe pattern)

vue的自定义事件和兄弟组件通讯就是通过这种方式来实现的

vue的自定义事件

    const vm = new Vue()
    vm.$on('datachange',()=>{
        cosnole.log('datachange')
    })
    vm.$on('datachange',()=>{
        cosnole.log('datachange2')
    })
    vm.$emit('datachange')

兄弟组件通讯过程

    // eventBus.js
    // 事件中心
    const eventBus = new Vue()
    
    // ComponentA.vue
    // 发布者
    addTodo:function () {
        // 发布消息
        eventBus.$emit('add-todo',{text:'hello word'})
    }
    
    // CompoentB.vue
    // 订阅者
    created:function () {
        //订阅消息
        eventBus.$on('add-todo',this.addTodo)
    }

模拟vue自定义事件

    // 事件触发器
    class EventEmitter {
       constructor () {
           this.subs = Object.create(null)
       }
       // 注册事件
        $on (eventType,handler) {
            this.subs[eventType] = this.subs[eventType]|| []
            this.subs[eventType].push(handler)
        }
        // 触发事件
        $emit (eventType,data) {
            if(!this.subs[eventType]) return
            this.subs[eventType].forEach(hander=>{
                hander(data)
            })
        }
    }
    const em = new EventEimtter()
    //注册事件
    em.$on('click',(data=>{
        cosole.log(data)
    })
    //触发事件
    em.$emit('click',{name:'wang'})