Skip to content

Instantly share code, notes, and snippets.

@daifu
Created July 3, 2012 05:39
Show Gist options
  • Save daifu/3037920 to your computer and use it in GitHub Desktop.
Save daifu/3037920 to your computer and use it in GitHub Desktop.
Javascript Web Application: PusSub Object
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;
}
};
@daifu
Copy link
Author

daifu commented Jul 3, 2012

To Test it:

PubSub.subscribe("wem", function () {
console.log("web!");
});
PubSub.publish("wem");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment