Skip to content

Instantly share code, notes, and snippets.

@danielbushman
Created February 10, 2012 05:58
Show Gist options
  • Save danielbushman/1787064 to your computer and use it in GitHub Desktop.
Save danielbushman/1787064 to your computer and use it in GitHub Desktop.
Javascript Homework Assignment
function PubSub() {
this.events = {};
}
PubSub.prototype = {
subscribe: function (e, callback, obj) {
if ( !this.events[e] ) this.events[e] = [];
if ( typeof(e) != "string" || typeof(callback) != "function" ) return false;
this.events[e].push({
callback: callback,
obj: obj
});
return true;
},
publish : function() {
var e = arguments[0],
args = 2 <= arguments.length ? Array().slice.call(arguments, 1) : [];
if ( typeof(e) != "string" || !this.events[e] ) return false;
var subscribers = this.events[e];
for ( var i in subscribers ) (function(subscribers, i){
setTimeout(function () {
subscribers[i].callback.apply(subscribers[i].obj, args);
}, 0);
})(subscribers, i);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment