Skip to content

Instantly share code, notes, and snippets.

@dxcqcv
Last active May 21, 2017 08:21
Show Gist options
  • Save dxcqcv/06406fce37d6f8fc6de93299537af46b to your computer and use it in GitHub Desktop.
Save dxcqcv/06406fce37d6f8fc6de93299537af46b to your computer and use it in GitHub Desktop.
Publish/Subscriber pattern
const pubsub = (function(){
let topics = {};
let subUid = -1;
let oneId = '';
function publish(topic, args) {
if(!topics[topic]) return false;
let subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while(len--) subscribers[len].func(topic, args);
return this;
}
function once(topic, func) {
oneId = subscribe(topic, function() {
func.apply(this, arguments);
unsubscribe(oneId);
});
return this;
}
function subscribe(topic, func) {
if(!topics[topic]) topics[topic] = [];
const token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
}
function unsubscribe(token) {
for(let topic in topics) {
if(!topic) return this;
topics[topic].splice(
topics[topic].indexOf(token),1
);
return token;
}
}
return {
on: subscribe,
off: unsubscribe,
one: once,
fire: publish
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment