Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Created July 19, 2017 13:29
Show Gist options
  • Save alexnoz/f62a6f105f5287ee009ad4066dbeab9d to your computer and use it in GitHub Desktop.
Save alexnoz/f62a6f105f5287ee009ad4066dbeab9d to your computer and use it in GitHub Desktop.
The "Publish-subscribe" pattern
const pubsub = (function () {
const topics = {};
let subUid = -1;
function publish (topic, args) {
if (!topics[topic])
return false;
const subscribers = topics[topic];
subscribers.forEach(sub => sub.func(topic, args))
return this;
};
function subscribe (topic, func) {
if (!topics[topic])
topics[topic] = [];
const token = (++subUid).toString();
topics[topic].push({
token,
func
});
return token;
};
function unsubscribe (token) {
for (let t in topics) {
if (topics[t]) {
for (let i = 0, j = topics[t].length; i < j; i++) {
if (topics[t][i].token === token) {
topics[t].splice(i, 1);
return token;
}
}
}
}
return this;
};
return {
publish,
subscribe,
unsubscribe
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment