Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Last active January 11, 2023 08:05
Show Gist options
  • Save joshuacerbito/9452c5b4e5c1361c541535b6e8e45758 to your computer and use it in GitHub Desktop.
Save joshuacerbito/9452c5b4e5c1361c541535b6e8e45758 to your computer and use it in GitHub Desktop.
Publish/Subscribe Snippet 2023
const PubSub = (() => {
const topics = {};
const hOP = topics.hasOwnProperty;
return {
subscribe(topic, listener) {
// Create the topic's object if not yet created
if(!hOP.call(topics, topic)) topics[topic] = [];
// Add the listener to queue
let 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(!hOP.call(topics, topic)){ return; }
// Cycle through topics queue, fire!
topics[topic].forEach(item => {
item(info != undefined ? info : {});
});
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment