Created
November 17, 2016 20:00
-
-
Save erikjoens/95287ebc367b442d5ecc28186c3ed283 to your computer and use it in GitHub Desktop.
Simple PubSub
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
var pubsub = function() { | |
var topics = {}, subUid = -1; | |
this.subscribe = function(topic, func) { | |
if (!topics[topic]) { | |
topics[topic] = []; | |
} | |
var token = (++subUid).toString(); | |
topics[topic].push({ | |
token: token, | |
func: func | |
}); | |
return token; | |
}; | |
this.publish = function(topic, args) { | |
if (!topics[topic]) { | |
return false; | |
} | |
setTimeout(function() { | |
var subscribers = topics[topic], | |
len = subscribers ? subscribers.length : 0; | |
while (len--) { | |
subscribers[len].func(topic, args); | |
} | |
}, 0); | |
return true; | |
}; | |
this.unsubscribe = function(token) { | |
for (var m in topics) { | |
if (topics[m]) { | |
for (var i = 0, j = topics[m].length; i < j; i++) { | |
if (topics[m][i].token === token) { | |
topics[m].splice(i, 1); | |
return token; | |
} | |
} | |
} | |
} | |
return false; | |
}; | |
this.getTopics = function() { | |
return topics; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment