2011-08-24 47 views
3

我希望能夠使用類似jQuery自定義事件和PubSubJS(http://github.com/mroderick/PubSubJS)中發現的pubsub機制。JS的基於主題的發佈/訂閱

問題是這些pubsub庫中的每一個都會在主題上完全匹配。 IO希望能夠發佈像一個主題:

"Order/Sent/1234" 

,並有聽訂閱兩種:

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

有誰知道像這樣的JS什麼?

回答

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]); 
     } 
     ... 
    } 
} 

您可能會需要修改了一下,這樣做替換所有*的與.*[^\/]* ...

+0

這種方法是有道理的,是我考慮的方法,但我想知道是否有更有效的方法。根據用戶數量的不同,這可能會非常低效。我希望如果已經有解決方案,他們已經解決了這種低效率問題。 –

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)) {才能滿足您的要求。