Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple message bus. Subscribe to a 'topic' and receive all messages published to that topic
// busloads of messages
let messages = {};
let messageBus = {
publish: (topic, message) => {
if(messages[topic]) {
messages[topic].push(message);
} else {
messages[topic] = [message]
}
},
subscribe: (topic, cb) => {
cb(messages[topic]);
},
};
// Messages w/ designated topic
messageBus.publish('new_signup', {'foo': 'bar', 'goo': 'gar'} );
messageBus.publish('user_loggedOut', {'user': 'jane doe'} );
// Subscribers to specified topics
messageBus.subscribe('new_signup', function(payload) {
if(payload) console.log(payload);
});
messageBus.subscribe('user_loggedOut', function(payload) {
if(payload) console.log(payload);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment