Created
October 26, 2017 16:58
-
-
Save kennyxcao/de046301246ffb0c95d56db42348465f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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