Skip to content

Instantly share code, notes, and snippets.

@kalisjoshua
Created August 16, 2016 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalisjoshua/e35b7ffeddba9d993853e4873f3a1834 to your computer and use it in GitHub Desktop.
Save kalisjoshua/e35b7ffeddba9d993853e4873f3a1834 to your computer and use it in GitHub Desktop.
function pubsubFactory() {
let subscribers = [];
const pub = publish;
const sub = subscribe;
const remove = unsubscribe;
function publish(message) {
if (!message) {
throw new Error('Not going to publish an empty message to subscribers.', 'pubsub.js');
}
subscribers
.forEach(x => x.fn(message));
}
function subscribe(fn) {
if (!fn || typeof fn !== 'function') {
throw new Error('Subscribe requires a Function as a subscription.', 'pubsub.js');
}
const id = Symbol(fn);
subscribers
.push({fn, id});
return id;
}
function unsubscribe(id) {
if (!id) {
throw new Error('An identifier is required for removing a subscription.', 'pubsub.js');
}
subscribers = subscribers
.filter(x => x.id !== id);
}
return {
publish,
subscribe,
unsubscribe,
pub,
sub,
remove
};
}
export default pubsubFactory;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment