Skip to content

Instantly share code, notes, and snippets.

@abdulapopoola
Last active November 7, 2016 06:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdulapopoola/5127673 to your computer and use it in GitHub Desktop.
Save abdulapopoola/5127673 to your computer and use it in GitHub Desktop.
PubSub implementation using closures in JavaScript
var makePubSub = function () {
var callbacks = {},
publish = function (){
//Turn arguments object into real array
var args = Array.prototype.slice.call(arguments, 0);
//Extract the event name which is the first entry
var ev = args.shift();
//Return if callbacks object doesn't contain
//any entry for event
var list, i, l;
if(!callbacks[ev]) { return this; }
list = callbacks[ev];
//Invoke the callbacks, passing in the rest of parameters
for (i=0, l=list.length; i<l; i=i+1){
list[i].apply(this, args);
}
return this;
},
subscribe = function (ev, callback){
//Check if ev is already registered
// If it isn't create an array entry for it
if(!callbacks[ev]){
callbacks[ev] = [];
}
callbacks[ev].push(callback);
return this;
};
return {pub: publish, sub: subscribe};
};
test = makePubSub()
test.sub('alert', function(){alert('hello');})
test.pub('alert')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment