Created
January 29, 2017 22:12
-
-
Save lewisrodgers/594e2641156cdcf7ec580e0da45163a8 to your computer and use it in GitHub Desktop.
Simple publish/subscribe implementation.
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
var Eventbus = { | |
topics: {}, | |
/** | |
* Adds topic to `topics` object if it doesn't exist | |
* and adds listener to same topic. | |
* | |
* @param {string} topic | |
* @param {function} listener | |
*/ | |
subscribe: function(topic, listener) { | |
if (!this.topics[topic]) { | |
// Add topic | |
this.topics[topic] = []; | |
} | |
//Add listener to topic | |
this.topics[topic].push(listener); | |
}, | |
/** | |
* Iterates over list of associated listeners for a topic. | |
* Data is passed to each listener when called. | |
* | |
* @param {string} topic the topic's label | |
* @param {string} data the listeners will do something with this on publish | |
*/ | |
publish: function(topic, data) { | |
// do nothing if topic doesn't exist or there are no listeners for topic. | |
if (!this.topics[topic] || this.topics[topic].length < 1) { | |
return; | |
} | |
// For each listener in topic... | |
this.topics[topic].forEach(function(listener) { | |
// call listener. | |
listener(data); | |
}) | |
} | |
} | |
// Listener | |
function say(msg) { | |
console.log(msg); | |
} | |
// Listener | |
function shout(msg) { | |
console.log(msg.toUpperCase() + '!!!!'); | |
} | |
// Subscribe listeners to 'message' topic. | |
Eventbus.subscribe('message', say); | |
Eventbus.subscribe('message', shout); | |
/** | |
* The `topics` object looks like this after a couple of subscribes: | |
* | |
* { 'message': [say, shout] } | |
* | |
* Eventbus will iterate over the topic array calling each listener | |
* and passing in the data. | |
*/ | |
Eventbus.publish('message', 'hello world'); // 'hello world', 'HELLO WORLD!!!!' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment