Skip to content

Instantly share code, notes, and snippets.

@sheljohn
Created September 15, 2017 01:11
Show Gist options
  • Save sheljohn/d328e683edf829c6e76d1034c0e91dda to your computer and use it in GitHub Desktop.
Save sheljohn/d328e683edf829c6e76d1034c0e91dda to your computer and use it in GitHub Desktop.
Publish/Subscribe singleton in JavaScript
/**
* Singleton publish/subscribe hub.
*/
module.exports = (function() {
const channel = {};
const noset = new Set();
return {
publish: (name,data) => {
(channel[name] || noset).forEach( fun => { fun(data); } )
},
subscribe: (name,fun) => {
if ( ! channel[name] ) {
channel[name] = new Set();
}
channel[name].add(fun);
},
unsubscribe: (name,fun) => {
(channel[name] || noset).delete(fun);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment