Created
June 12, 2014 18:25
-
-
Save sbruchmann/6522769715e0c09ee9d3 to your computer and use it in GitHub Desktop.
Minimal PubSub solution
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
// Original code by David Walsh: http://davidwalsh.name/pubsub-javascript | |
var events = (function(){ | |
var topics = {}; | |
return { | |
subscribe: function(topic, listener) { | |
// Create the topic's object if not yet created | |
if(!topics[topic]) topics[topic] = { queue: [] }; | |
// Add the listener to queue | |
var index = topics[topic].queue.push(listener); | |
// Provide handle back for removal of topic | |
return (function(index) { | |
return { | |
remove: function() { | |
delete topics[index]; | |
} | |
} | |
})(index); | |
}, | |
publish: function(topic, info) { | |
// If the topic doesn't exist, or there's no listeners in queue, just leave | |
if(!topics[topic] || !topics[topic].queue.length) return; | |
// Cycle through topics queue, fire! | |
var items = topics[topic].queue; | |
for(var x = 0; x < items.length; x++) { | |
items[x](info || {}); | |
} | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment