简单实现发布订阅模式

发布订阅模式,基于一个主题/事件通道,希望接收通知的对象(subscriber)通过自定义事件订阅主题,被激活事件对象(publisher)通过发布主题事件的方式被通知。

js中的事件监听机制就是一种观察者模式

export default class Oberver {
  // 定义一个事件容器
  event = {}

  subscribe (type, fn) {
    // 消息类型不存在
    if (typeof this.event[type] === 'undefined') {
      this.event[type] = [fn]
    // 存在,将fn推入事件队列
    } else {
      this.event[type].push(fn)
    }
  }

  publish (type, args = {}) {
    // 消息类型没人订阅
    if (!this.event[type]) return
    let i = 0
    let len = this.event[type].length
    for (; i < len; i++) {
      // 依次执行事件队列(发布)
      this.event[type][i].call(this, {type, args})
    }
  }
}
原文地址:https://www.cnblogs.com/theblogs/p/10474245.html