Created
December 11, 2017 13:38
-
-
Save dutchcelt/ef8d3b415c28f7bf6cbe4831b462ed7c to your computer and use it in GitHub Desktop.
Very basic Pub/Sub
This file contains hidden or 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
/** | |
* 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