Created
June 24, 2014 05:18
-
-
Save srijanshetty/b675ab657c1052cd6ba0 to your computer and use it in GitHub Desktop.
Pub Sub system
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
// Taken from David Walsh's blog | |
var events = (function() { | |
var topics = {}; | |
return { | |
subscribe: function(topic, listener) { | |
if (!topics[topic]) { | |
topics[topic] = { | |
queue: [] | |
}; | |
} | |
var index = topics[topic].queue.push(listener); | |
return (function (index) { | |
return { | |
remove: function() { | |
delete topics[topic].queue[index] | |
} | |
}; | |
})(index); | |
}, | |
publish: function(topic, info) { | |
if( !topics[topic] || !topics[topic].queue.length) { | |
return ; | |
} | |
topics[topic].queue.forEach(function(element) { | |
element(info || {}); | |
}); | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment