Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Last active March 3, 2021 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuacerbito/3596f878be4f8676fca4570142f0c0ac to your computer and use it in GitHub Desktop.
Save joshuacerbito/3596f878be4f8676fca4570142f0c0ac to your computer and use it in GitHub Desktop.
A topic-based subscribe-publish library written in JavaScript.
/*
* Observer.js
*
* SYNTAX:
* const EventHandler = new MessageBus( context );
* ---
* context: identifier for the event handler
* ---
* USAGE:
* var handler = new MessageBus( document );
*/
function MessageBus(id) {
const context = typeof id === "undefined" ? document : id;
const topics = {};
const hOP = topics.hasOwnProperty;
return {
subscribe: function(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: function() {
delete topics[topic][index];
}
};
},
publish: function(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(function(item) {
item(info !== undefined ? info : {});
});
}
};
}
export default MessageBus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment