js实现发布订阅模式

一、发布订阅模式和观察者模式的区别

1.观察者和目标要相互知道
2.发布者和订阅者不用互相知道,通过第三方实现调度,属于经过解耦合的观察者模式

    /**
    * 发布订阅模式
    * handles: 事件处理函数集合
    * on: 订阅事件
    * emit: 发布事件
    * off: 删除事件
    **/
    class PubSub {
      constructor() {
        this.handles = {};
      }

      // 订阅事件
      on (eventType, handle) {
        if (!this.handles.hasOwnProperty(eventType)) {
          this.handles[eventType] = [];
        }
        if (typeof handle == 'function') {
          this.handles[eventType].push(handle);
        } else {
          throw new Error('缺少回调函数');
        }
        return this;
      }

      // 发布事件
      emit (eventType, ...args) {
        if (this.handles.hasOwnProperty(eventType)) {
          this.handles[eventType].forEach((item, key, arr) => {
            item.apply(null, args);
          })
        } else {
          throw new Error(`"${eventType}"事件未注册`);
        }
        return this;
      }

      // 删除事件
      off (eventType, handle) {
        if (!this.handles.hasOwnProperty(eventType)) {
          throw new Error(`"${eventType}"事件未注册`);
        } else if (typeof handle != 'function') {
          throw new Error('缺少回调函数');
        } else {
          this.handles[eventType].forEach((item, key, arr) => {
            if (item == handle) {
              arr.splice(key, 1);
            }
          })
        }
        return this; // 实现链式操作
      }
    }

    // 下面做一些骚操作
    let callback = function () {
      console.log('you are so nice');
    }
    let pubsub = new PubSub();
    pubsub.on('completed', (...args) => {
      console.log(args.join(' '));
    })
    pubsub.on('completed', callback);
    pubsub.emit('completed', 'what', 'a', 'fucking day');
    pubsub.off('completed', callback);
    pubsub.emit('completed', 'what', 'a', 'fucking day');
    // 控制台打印
    // what a fucking day
    // you are so nice
    // what a fucking day
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发布-订阅模式中存在三种角色,发布者、订阅者,二者彼此不知道对方的存在,需要通过第三者,即消息队列来建立联系。这和...
    凯凯frank阅读 4,318评论 0 1
  • 定义 观察者模式一个或多个观察者对目标的状态感兴趣,通过将自己依附在目标对象上以便注册所感兴趣的内容。目标状态发生...
    747大雄阅读 3,599评论 0 0
  • 定义:订阅发布模式定义了对象间一种一对多的关系,让多个观察者对象同时监听同一主题对象,当一个对象改变时,所有依赖于...
    Splendid飞羽阅读 5,108评论 0 1
  • 什么是发布订阅模式?能手写实现一下吗?它和观察者模式有区别吗?... 1 场景引入 我们先来看这么一个场景: 假设...
    程序员既明阅读 1,209评论 0 0
  • 发布订阅 订阅发布模式定义了一种一对多的依赖关系,让多个订阅者对象同时监听某一个主题对象。这个主题对象在自身状态变...
    一包阅读 1,170评论 0 0