Last active
January 11, 2023 08:05
-
-
Save joshuacerbito/9452c5b4e5c1361c541535b6e8e45758 to your computer and use it in GitHub Desktop.
Publish/Subscribe Snippet 2023
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 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