首页 > 其他 > 详细

简单实现发布订阅模式

时间:2019-03-05 00:38:12      阅读:196      评论:0      收藏:0      [点我收藏+]

发布订阅模式,基于一个主题/事件通道,希望接收通知的对象(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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!