Last active
June 1, 2017 17:52
-
-
Save alexitaylor/0ea8c1d39e20f96db88d1279e27fed60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prompt: https://gist.github.com/tim-hr/697af278700fcf12014eb36d932ad7c4 | |
var messageBus = { | |
subscribers: [], | |
subscribe: function(payload) { | |
this.subscribers.push(payload); | |
}, | |
publish: function(payload) { | |
this.subscribers.forEach(function(sub){ | |
if (validTopic(payload.topic, sub.topic) && payload.channel === sub.channel) { | |
sub.callback(payload.data); | |
} | |
}); | |
}, | |
}; | |
var validTopic = function(pubTopic, subTopic) { | |
if (subTopic[subTopic.length - 1] === '*'){ | |
var subTopicPrefix = subTopic.slice(0, -1); | |
var pubTopicPrefix = pubTopic.slice(0, subTopic.length - 1); | |
if (pubTopicPrefix === subTopicPrefix) { | |
return true; | |
} | |
} else if (subTopic === pubTopic) { | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
// Subscriber subscribes with wildcarding | |
messageBus.subscribe({ | |
channel: 'commerce', | |
topic: 'order_*', | |
callback: function(payload) { | |
// do something with the payload | |
console.log(payload); | |
} | |
}); | |
// Publisher publishes as normal (no wildcarding on this side) | |
messageBus.publish({ | |
channel: 'commerce', | |
topic: 'order_started', | |
data: { | |
user_id: '4273984723428' | |
} | |
}); | |
// The above subscriber receives this message. | |
messageBus.publish({ | |
channel: 'commerce', | |
topic: 'order_complete', | |
data: { | |
plan_level: 'GOLD', | |
user_id: '4273984723428' | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment