发布订阅

115 阅读1分钟

发布订阅(Publish-Subscribe)- 设计模式

发布订阅是一种常用的设计模式,它用于处理多个组件之间的通信,使得这些组件之间不需要显示的相互引用。在这种模式中,组件之间通过一个共享的中心机制(事件中心)来进行通信,这个中心机制负责接收消息并将其广播给订阅该消息的所有组件。

实现思路

  1. 创建一个事件中心对象,用来管理订阅和发布消息;
  2. 组件可以通过订阅事件中心来注册自己的消息处理函数;
  3. 组件可以通过向事件中心发布消息来触发订阅该消息的所有组件的处理函数;

示例

const eventHub = {
    map: {
    // click: [f1, f2]
    },
    
    on: (name, fn) => {
        eventHub.map[name] = eventHub.map[name] || []
        eventHub.map[name].push(fn)
    },
    
    emit: (name, ...args) => {
        const q = eventHub.map[name]
        if (!q) return
        q.map(f => {
            f.call(null, ...args)
        })
    },
    
    off: (name, fn) => {
        const q = eventHub.map[name]
        if (!q) return
        const index = q.indexOf(fn)
        if (index < 0) return
        q.splice(index, 1)
    },
}

使用 class 实现

class EventHub {
  map = {}
  on(name, fn) {
    this.map[name] = this.map[name] || []
    this.map[name].push(fn)
  }
  emit(name, ...args) {
    const fnList = this.map[name] || []
    fnList.forEach(fn => fn.call(undefined, ...args))
  }
  off(name, fn) {
    const fnList = this.map[name] || []
    const index = fnList.indexOf(fn)
    if(index < 0) return
    fnList.splice(index, 1)
  }
}