我希望能够拥有类似于jQuery自定义事件和PubSubJS(http://github.com/mroderick/PubSubJS)中的pubsub机制。
问题在于,这些pubsub库中的每一个都会对主题进行精确匹配。但我希望能够发布像下面这样的主题:
"Order/Sent/1234"
请订阅以下任一链接以收听:
"Order/Sent/1234"
"Order/Sent/*"
"Order/*/1234"
有没有类似于这样的JS工具?
我希望能够拥有类似于jQuery自定义事件和PubSubJS(http://github.com/mroderick/PubSubJS)中的pubsub机制。
问题在于,这些pubsub库中的每一个都会对主题进行精确匹配。但我希望能够发布像下面这样的主题:
"Order/Sent/1234"
请订阅以下任一链接以收听:
"Order/Sent/1234"
"Order/Sent/*"
"Order/*/1234"
只需修改您喜欢的那个。在 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] );
}
...
}
}
你可能需要稍微修改一下,比如将所有的*
替换为.*
或[^\/]*
,然后再转换为正则表达式等等...
// 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)) {
以满足您的要求。