pubsub
This commit is contained in:
46
pubsub.js
46
pubsub.js
@@ -1,11 +1,43 @@
|
||||
const app = require('./app');
|
||||
class PubSub{
|
||||
constructor(){
|
||||
this.topics = {};
|
||||
}
|
||||
|
||||
app.p2p.onData(function(data){
|
||||
console.log('app, data:', data)
|
||||
})
|
||||
subscribe(topic, listener) {
|
||||
if(topic instanceof RegExp){
|
||||
listener.match = topic;
|
||||
topic = "__REGEX__";
|
||||
}
|
||||
|
||||
// create the topic if not yet created
|
||||
if(!this.topics[topic]) this.topics[topic] = [];
|
||||
|
||||
setTimeout(function(){
|
||||
app.p2p.broadcast({type:'topic', body:"yolo"})
|
||||
}, 10000);
|
||||
// add the listener
|
||||
this.topics[topic].push(listener);
|
||||
}
|
||||
|
||||
matchTopics(topic){
|
||||
let topics = [... this.topics[topic] ? this.topics[topic] : []]
|
||||
|
||||
// console.log(this.topics)
|
||||
if(!this.topics['__REGEX__']) return topics;
|
||||
|
||||
for(let listener of this.topics['__REGEX__']){
|
||||
if(topic.match(listener.match)) topics.push(listener);
|
||||
}
|
||||
|
||||
return topics;
|
||||
}
|
||||
|
||||
publish(topic, data) {
|
||||
|
||||
// send the event to all listeners
|
||||
this.matchTopics(topic).forEach(function(listener) {
|
||||
setTimeout(function(data, topic){
|
||||
listener(data || {}, topic);
|
||||
}, 0, data, topic);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {PubSub};
|
||||
|
||||
Reference in New Issue
Block a user