Skip to content

Instantly share code, notes, and snippets.

@jgilless

jgilless/pubsub.js

Created May 6, 2019
Embed
What would you like to do?
/**
* @param { Function } reducer
* @param { Object } initialState
* @returns { Store } State
*/
function createPubSub() {
let messages = {};
/**
* Publish publishes messages
* @param { String } message
* @param { Object } payload
*/
function publish(message, payload) {
// loop through messages on the message and fire the listener
if (messages[message].length === 0) {
return;
}
messages[message].forEach(function(subscription) {
subscription(payload !== undefined ? payload : {});
});
}
/**
* Subscribe subscribes to messages
* @param { String } message
* @param { Function } handler
* @return { Function } unsubscribe
*/
function subscribe(message, handler) {
if (!messages.hasOwnProperty(message)) {
messages[message] = [];
}
const index = messages[message].push(handler) - 1;
function unsubscribe() {
delete messages[message][index];
}
return {
unsubscribe
};
}
return {
publish,
subscribe
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment