Skip to content

Instantly share code, notes, and snippets.

@jrcryer
Created October 16, 2012 23:01
Show Gist options
  • Save jrcryer/3902614 to your computer and use it in GitHub Desktop.
Save jrcryer/3902614 to your computer and use it in GitHub Desktop.
Simple JavaScript Pub/Sub object
var PubSub = {
subscribe: function(ev, callback) {
var calls = this._callbacks || (this._callbacks = {});
(this._callbacks[ev] || (this._callbacks[ev] = [])).push(callback);
return this;
},
publish: function() {
var args = Array.prototype.slice.call(arguments, 0);
var ev = args.shift();
var list, calls, i, l;
if(!(calls = this._callbacks)) return this;
if(!(list = this._callbacks[ev])) return this;
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