侧边栏壁纸
  • 累计撰写 35 篇文章
  • 累计收到 1 条评论

js 发布订阅

逸曦穆泽
2022-05-12 / 0 评论 / 12 阅读 / 正在检测是否收录...
发布订阅是一种消息范式,消息的发送者(称为发布者)不会将消息直接发送给特定的接收者(称为订阅者)。

发布的消息分为不同的类别,无需了解哪些订阅者的存在。同样的,订阅者可以表达对一个或多个类别的兴趣,只接收感兴趣的消息,无需了解哪些发布者的存在。

2.发布者和订阅者不用互相知道,通过第三方实现调度,属于经过解耦合的观察者模式
    /**
    * 发布订阅模式
    * handles: 事件处理函数集合
    * on: 订阅事件
    * emit: 发布事件
    * off: 删除事件
    **/
    class EventBus {
      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 eventBus = new EventBus();
    eventBus.on('key', (...args) => {
      console.log(args.join(' '));
    })
    eventBus.on('key', 'ni hao ma');
    eventBus.emit('key', 'hao', 'tian', 'zhen');
    eventBus.off('key', 'ni hao ma');
    eventBus.emit('key', 'hao', 'tian', 'zhen');
这个暂时还没用到,下次记录一个用到的
0

评论 (0)

取消