基于主题的pub / sub for JS

时间:2011-08-24 18:47:02

标签: javascript wildcard publish-subscribe

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

问题是这些pubsub库中的每一个都与主题完全匹配。 IO希望能够发布如下主题:

"Order/Sent/1234"

请听一下订阅:

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

有没有人知道JS这样的事情?

2 个答案:

答案 0 :(得分:0)

只需修改你喜欢的那个。将它放在github上,打开pubsub.js并执行以下操作:

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

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

您可能需要稍微修改一下,在转换为正则表达式等之前执行诸如将所有*替换为.*[^\/]*之类的内容...

答案 1 :(得分: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)) {以满足您的要求。