【问题标题】:Topic based pub/sub for JS基于主题的 JS 发布/订阅
【发布时间】:2011-11-03 02:01:48
【问题描述】:

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

问题在于这些 pubsub 库中的每一个都在主题上进行了完全匹配。 IO 希望能够发布这样的主题:

"Order/Sent/1234"

并且有一个听订阅:

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

有没有人知道类似 JS 的东西?

【问题讨论】:

    标签: javascript wildcard publish-subscribe


    【解决方案1】:
        // 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)) { 以满足您的要求。

    【讨论】:

      【解决方案2】:

      只要修改你喜欢的那个。在 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] );
              }
              ...
          }
      }
      

      您可能需要稍微修改一下,在转换为正则表达式之前,先将所有* 替换为.*[^\/]*,等等...

      【讨论】:

      • 这种方法是有道理的,是我考虑过的,但我想知道是否有更有效的方法。根据订阅者的数量,这可能非常低效。我希望如果已经有解决方案,他们已经解决了这种低效率问题。
      猜你喜欢
      • 2018-02-19
      • 2017-05-07
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多