Skip to content

Instantly share code, notes, and snippets.

@JamieDixon
Created July 3, 2014 20:47
Show Gist options
  • Save JamieDixon/fbff9fc44ad63e28549c to your computer and use it in GitHub Desktop.
Save JamieDixon/fbff9fc44ad63e28549c to your computer and use it in GitHub Desktop.
Basic PubSub
window.pubSub = window.pubSub || {};
(function IFEE(pubSub) {
'use strict';
var eventStore = {}, lastId = 0;
pubSub.subscribe = function sub(topic, func) {
if (!eventStore.hasOwnProperty(topic)) {
eventStore[topic] = {}; // Was using an array but this seems better for unsub perf.
}
lastId += 1; // arrg @ possible race cond. Keeping incrimental ID gen for simplicity of gist.
eventStore[topic][lastId] = func;
return lastId;
};
pubSub.unsubscribe = function unsub(id) {
var events, topic;
for (topic in eventStore)
{
if (eventStore.hasOwnProperty(topic))
{
events = eventStore[topic];
delete events[id];
}
}
};
pubSub.publish = function pub(topic) {
var events, args, callback;
if (eventStore.hasOwnProperty(topic)) {
events = eventStore[topic];
args = Array.prototype.slice.call(arguments).splice(1, arguments.length);
for (callback in events)
{
if (events.hasOwnProperty(callback))
{
events[callback].apply(this, args);
}
}
}
};
pubSub.viewEvents = function () {
return eventStore;
};
}(window.pubSub));
///// USAGE
(function IFEE (pubSub) {
'use strict';
pubSub.subscribe('index/loaded', function (time, from) {
console.log("The loaded event was called at ", time, " from ", from);
});
pubSub.subscribe('index/loaded', function () {
console.log("I'm alive!");
});
pubSub.subscribe('index/afterLoaded', function () {
console.log("We made it through. Thanks heavens for that.");
});
var pubId = pubSub.subscribe('index/loaded', function () {
console.log("My time here is somewhat limited");
});
pubSub.unsubscribe(pubId);
function init() {
pubSub.publish('index/loaded', new Date().getTime(), "index");
}
init();
pubSub.publish('index/afterLoaded');
console.log(pubSub.viewEvents());
}(window.pubSub));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment