Skip to content

Instantly share code, notes, and snippets.

@Adam-Mould
Created July 23, 2018 13:18
Show Gist options
  • Save Adam-Mould/27927f135b6403098724c6a84f7e2458 to your computer and use it in GitHub Desktop.
Save Adam-Mould/27927f135b6403098724c6a84f7e2458 to your computer and use it in GitHub Desktop.
const events = (function () {
const topics = {};
return {
subscribe(topic, listener) {
// Create topics object if not yet created
if (!topics.hasOwnProperty.call(topics, topic)) topics[topic] = [];
// Add listener to the queue
const index = topics[topic].push(listener) - 1;
// Provide handle back for removal of topic
return {
remove() {
delete topics[topic][index];
},
};
},
publish(topic, info = {}) {
// If the topic doesn't exist, or there's no listeners in queue, just leave
if (!topics.hasOwnProperty.call(topics, topic)) return;
// Cycle through topics queue, fire!
topics[topic].forEach(item => item(info));
},
};
}());
export default events;
@Adam-Mould
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment