Last active
November 7, 2016 06:16
-
-
Save abdulapopoola/5127673 to your computer and use it in GitHub Desktop.
PubSub implementation using closures in JavaScript
This file contains hidden or 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 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