基于主题的JS发布/订阅模式

3

我希望能够拥有类似于jQuery自定义事件和PubSubJS(http://github.com/mroderick/PubSubJS)中的pubsub机制。

问题在于,这些pubsub库中的每一个都会对主题进行精确匹配。但我希望能够发布像下面这样的主题:

"Order/Sent/1234"

请订阅以下任一链接以收听:

"Order/Sent/1234"
"Order/Sent/*"
"Order/*/1234"

有没有类似于这样的JS工具?
2个回答

0

只需修改您喜欢的那个。在 Github 上 fork 它,打开 pubsub.js 并进行如下操作:

var deliverMessage = function(){
    var subscribers = [];

    for(var n in messages){
        if( new RegExp('^' + n + '$').test( message ) ){
            subscribers = subscribers.concat( messages[n] );
        }
        ...
    }
}

你可能需要稍微修改一下,比如将所有的*替换为.*[^\/]*,然后再转换为正则表达式等等...


这种方法很有道理,我也考虑过,但我想知道是否有更有效率的方法。根据订阅者的数量,这可能非常低效。我希望如果已经有解决方案,他们已经解决了这个低效性问题。 - vdh_ant

0
    // Paytm's turbo churged Publish - Subscribe Library

export const PaytmConnect = (() => {
  const topics = {};

  return {
    subscribe: (topic, listener) => {
      // Create the topic's object if not yet created
      if (!topics.hasOwnProperty(topic)) topics[topic] = [];

      // Add the listener to queue
      const index = topics[topic].push(listener) - 1;

      // Provide handle back for removal of topic
      return {
        remove: () => {
          delete topics[topic][index];
        }
      };
    },
    publish: (topic, info) => {
      // If the topic doesn't exist, or there's no listeners in queue, just leave
      if (!topics.hasOwnProperty(topic)) return;
      const allProperty = Object.getOwnPropertyNames(topic);
      allProperty.forEach((property) => {
        if (property.match(topic)) {
          // Cycle through topics queue, fire!
          topics[topic].forEach((item) => {
            item(info !== undefined ? info : {});
          });
        }
      });
    }
  };
})();

您需要稍微修改代码if (property.match(topic)) {以满足您的要求。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接