2011-08-24 2 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)) {를 조금 수정해야합니다.