Skip to content

Instantly share code, notes, and snippets.

@dutchcelt
Created December 11, 2017 13:38
Show Gist options
  • Save dutchcelt/ef8d3b415c28f7bf6cbe4831b462ed7c to your computer and use it in GitHub Desktop.
Save dutchcelt/ef8d3b415c28f7bf6cbe4831b462ed7c to your computer and use it in GitHub Desktop.
Very basic Pub/Sub
/**
* Very simple Pub/Sub implementation using Symbols and setImmediate.
*/
const topics = {};
const getTokens = (str, obj) => Object.getOwnPropertySymbols(obj).filter(t => t.toString() === `Symbol(${str})`);
export default {
subscribe: (topic, listener) => {
const token = Symbol(topic);
topics[token] = listener;
return token;
},
unsubscribe: token => {
delete topics[token];
},
publish: (topic, data) => {
getTokens(topic, topics).forEach(token => {
setImmediate(topics[token], data);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment