忘却录音——订阅&发布

同步篇

发布订阅在开发中是十分常见的一种设计模式,包括 Vue 在内很多框架本身就直接集成了发布订阅功能,初入框架学习的小白可能只会单纯使用,并不清楚发布订阅究竟有多少种模式,以及每种模式的实现原理,本篇就简单介绍一下发布订阅的实现原理。

SyncHook

首先写一个最简单的发布订阅类:

// 发布订阅类
class SyncHook {
  constructor() {
    this.tasks = [];
  }
  tap(task) {
    this.tasks.push(task);
  }
  call(...messages) {
    for (let task of this.tasks) task(...messages);
  }
}

// 创建发布者
const synchook = new SyncHook();
// 订阅发布者的消息
synchook.tap((a, b) => {
  console.log("a", a, b);
});
synchook.tap((a, b) => {
  console.log("b", a, b);
});
// 发布者发布消息
synchook.call("hello", "world");

发布订阅类初始化时会创建一个空的回调数组,每次出现订阅时将回调函数放入数组,这样发布消息时只需遍历数组调用回调函数,同时传入参数即可,使用扩展运算符是因为传入参数的数量可能为任意个。这样一个大体的发布订阅功能就完成了。

但如果想要区分事件的类型呢?这种需求也是很常见的,比如在使用 Vue 相关的组件库时,经常会出现监听子组件不同的事件,那么只需将回调数组改为一个对象即可,对象的每一个 key 就是一个事件类型,key 对应的数组就是发布该事件的消息时需要遍历调用的回调函数,同时因为发布订阅类本身并不知道具体都有哪些事件,所以这些事件应该是由订阅函数动态创建。

class SyncHook {
  constructor() {
    this.tasks = {};
  }
  tap(event, task) {
    if (!this.tasks[event]) this.tasks[event] = [];
    this.tasks[event].push(task);
  }
  call(event, ...messages) {
    const taskes = this.tasks[event];
    for (let task of taskes) task(...messages);
  }
}

const synchook = new SyncHook();
synchook.tap("a", (a, b) => {
  console.log("a", a, b);
});
synchook.tap("b", (a, b) => {
  console.log("b", a, b);
});
synchook.call("a", "hello", "world");

这样就只有订阅 a 事件的订阅者会收到消息了。而 SyncHook 的意思是同步串行的钩子,不关心订阅回调函数的返回值,在触发消息之后会按照订阅的先后顺序执行所有的订阅函数。那么显然,发布订阅不止这一种模式,本文介绍的所有的发布订阅模式,都是Tapable中对应模式的简单实现,Tapable 功能更全面复杂校验也更加完善等等,但直接用 Tapable 源码讲解不易于理解,所以在理解本篇以后想要深入学习,可以去阅读 Tapable 源码。

另外,Tapable 其实并不关心订阅的事件,反而在 new 时会传一个字符串数组作为参数,长度就是之后触发消息时的参数个数,每个字符串就是对应参数含义的描述,而很多发布订阅的库都是基于 Tapable 各种模式的再封装,加入了订阅事件的区别。

class SyncHook {
  constructor(event) {
    this.tasks = [];
    this.arguments = event || [];
  }
  tap(event, task) {
    this.tasks.push(task);
  }
  call(...messages) {
    if (messages.length < this.arguments.length)
      return new Error("参数个数不对");
    messages = messages.slice(0, this.arguments.length);
    for (let task of this.tasks) task(...messages);
  }
}

但本文将采用区分事件的发布订阅,对参数个数不做严格规范。

SyncBailHook

SyncBailHook 也是同步串行的钩子,同样会在触发消息之后按照订阅的先后顺序执行订阅函数,但 SyncBailHook 关心返回值,如果出现一个订阅函数返回值不为 undefined,那么后续的函数将不再执行。

只需在遍历时候,判断每一个函数的返回值,如果不为 undefined 的话,就 break 循环即可。

class SyncBailHook {
  constructor() {
    this.tasks = {};
  }
  tap(event, task) {
    if (!this.tasks[event]) this.tasks[event] = [];
    this.tasks[event].push(task);
  }
  call(event, ...messages) {
    const taskes = this.tasks[event];
    for (let task of taskes) {
      const result = task(...messages);
      if (result !== undefined) break;
    }
  }
}

const syncbailhook = new SyncBailHook();
syncbailhook.tap("a", (a, b) => {
  console.log(1, a, b);
});
syncbailhook.tap("a", (a, b) => {
  console.log(2, a, b);
  return undefined;
});
syncbailhook.tap("a", (a, b) => {
  console.log(3, a, b);
  return 3;
});
syncbailhook.tap("a", (a, b) => {
  console.log(4, a, b);
});
syncbailhook.call("a", "hello", "world");

可以看出,因为第 3 个订阅函数返回不是 undefined,所以第四个订阅函数没有执行。

SyncWaterfallHook

SyncBailHook 同样是按照订阅的先后顺序执行的同步串行钩子,也同样关心订阅函数的返回值,但会将前一个订阅函数的返回值传递给下一个函数。

只需对第一个订阅函数的传参单独处理,其它的依次遍历传入前一个函数的返回值即可。

class SyncWaterfallHook {
  constructor() {
    this.tasks = {};
  }
  tap(event, task) {
    if (!this.tasks[event]) this.tasks[event] = [];
    this.tasks[event].push(task);
  }
  call(event, ...messages) {
    //   利用解构赋值单独取出第一个,并将后续装入 others 数组
    const [first, ...others] = this.tasks[event];
    let result = first(...messages);
    for (let task of others) result = task(result);
  }
}

const syncwaterfallhook = new SyncWaterfallHook();
syncwaterfallhook.tap("a", (a, b) => {
  console.log(1, a, b);
  return m.join(" ") + 1;
});
syncwaterfallhook.tap("a", (a) => {
  console.log(2, a);
  return m + 2;
});
syncwaterfallhook.tap("a", (a) => {
  console.log(3, a);
  return m + 3;
});
syncwaterfallhook.call("a", "hello", "world");

SyncLoopHook

SyncLoopHook 同样是同步串行钩子,它关心订阅函数返回值的不同点在于,如果当前的订阅函数的返回值不是 undefined,就会一直执行该订阅函数。

只需在遍历到每一个订阅函数时,再加一个 do while 循环,并在 do while 循环中取出每次调用的返回值判断即可。

为了防止陷入死循环,先定义一个 count 变量,让第 1 个执行函数执行 3 遍,第 2 个执行两遍,第 3 个执行 1 遍。

class SyncLoopHook {
  constructor() {
    this.tasks = {};
  }
  tap(event, task) {
    if (!this.tasks[event]) this.tasks[event] = [];
    this.tasks[event].push(task);
  }
  call(event, ...messages) {
    const tasks = this.tasks[event];
    for (let task of tasks) {
      let result = undefined;
      do {
        result = task(...messages);
      } while (result !== undefined);
    }
  }
}

let count = 0;
const syncloophook = new SyncLoopHook();
syncloophook.tap("a", (a, b) => {
  console.log(1, a, b);
  count += 1;
  return count < 3 ? "" : undefined;
});
syncloophook.tap("a", (a, b) => {
  console.log(2, a, b);
  count += 1;
  return count < 5 ? "" : undefined;
});
syncloophook.tap("a", (a, b) => {
  console.log(3, a, b);
  return undefined;
});
syncloophook.call("a", "hello", "world");

至此,所有同步的发布订阅模式都介绍完毕。但在开发中,不可避免地存在很多异步的发布订阅的需求,这样的话就需要每一个订阅函数告知发布订阅类,自己是否执行完毕以及是否要执行下一个订阅函数。这个将会放在另一篇博客中介绍

你可能感兴趣的:(忘却录音——订阅&发布)