Created
February 10, 2012 05:58
-
-
Save danielbushman/1787064 to your computer and use it in GitHub Desktop.
Javascript Homework Assignment
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
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