Created
August 16, 2016 18:42
-
-
Save kalisjoshua/e35b7ffeddba9d993853e4873f3a1834 to your computer and use it in GitHub Desktop.
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
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