Created
July 23, 2018 13:18
-
-
Save Adam-Mould/27927f135b6403098724c6a84f7e2458 to your computer and use it in GitHub Desktop.
This file contains 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
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://davidwalsh.name/pubsub-javascript