Created
July 3, 2012 05:39
-
-
Save daifu/3037920 to your computer and use it in GitHub Desktop.
Javascript Web Application: PusSub Object
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 = { | |
subscribe: function(ev, callback) { | |
// Create _callbacks object, unless it already exists | |
var calls = this._callbacks || (this._callbacks = {}); | |
// Create an array for the given event key, unless it exists, then | |
// append the callback to the array | |
(this._callbacks[ev] || (this._callbacks[ev] = [])).push(callback); | |
return this; | |
}, | |
publish: function() { | |
// Turn arguments object into a real array | |
var args = Array.prototype.slice.call(arguments, 0); | |
// Extract the first argument, the event name | |
var ev = args.shift(); | |
// Return if there isn't a _callbacks object, or | |
// if it doesn't contain an array for the given event | |
var list, calls, i, l; | |
if (!(calls = this._callbacks)) return this; | |
if (!(list = this._callbacks[ev])) return this; | |
// Invoke the callbacks | |
for (i = 0, l = list.length; i < l; i++) | |
list[i].apply(this, args); | |
return this; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To Test it:
PubSub.subscribe("wem", function () {
console.log("web!");
});
PubSub.publish("wem");