发布订阅者模式的简版

// 发布者 订阅者模式
const pubsub = (() => {
  const topics = {};
  // 订阅
  function subscribe(topic) {
    if (!topics[topic]) {
      topics[topic] = [];
    }
    topics[topic] = function (a) {
      console.log(a)
    }
  }
  // 发布
  function publish(topic, ...args) {
    if (!topics[topic]) return;
    for (let param of args) {
      topics[topic](param);
    }
  }
  return {
    subscribe,
    publish
  }
})();
pubsub.subscribe('test');
pubsub.publish('test', 'HH', '123', '345'); // HH 123 345
pubsub.subscribe('test1')

你可能感兴趣的:(发布订阅者模式的简版)