Skip to content

Instantly share code, notes, and snippets.

@kennyxcao
Created October 26, 2017 16:58
Show Gist options
  • Save kennyxcao/de046301246ffb0c95d56db42348465f to your computer and use it in GitHub Desktop.
Save kennyxcao/de046301246ffb0c95d56db42348465f to your computer and use it in GitHub Desktop.
// Make a message bus object for use in your client-side (in-browser) code.
// The name (label) of a message type should be called the topic, in your code. This is standard pub/sub nomenclature.
// The payload is optional.
// Subscribers must be notified in the exact order that they originally subscribed.
// inside component A...
// messageBus.subscribe('new_signup', function(payload) {
// // do something with the payload
// });
// inside component B...
// messageBus.publish('new_signup', {'foo': 'bar', 'goo': 'gar'} );
const messageBus = {
topics: {},
subscribe: function(topic, listener) {
if (!this.topics[topic]) {
this.topics[topic] = [];
}
console.log(topic);
this.topics[topic].push(listener);
},
publish: function(topic, payload) {
if (!(this.topics[topic])) {
return;
}
this.topics[topic].forEach(listener => {
listener(payload !== undefined ? payload : {});
})
}
}
// Tests
//inside component A...
messageBus.subscribe('new_signup', function(payload) {
console.log(payload);
});
// inside component B...
messageBus.publish('new_signup', {'foo': 'bar', 'goo': 'gar'} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment