Created
September 15, 2017 01:11
-
-
Save sheljohn/d328e683edf829c6e76d1034c0e91dda to your computer and use it in GitHub Desktop.
Publish/Subscribe singleton in JavaScript
This file contains 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
/** | |
* 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