Created
January 30, 2015 17:48
-
-
Save valerysntx/b5c71b9e604b8a7a36d1 to your computer and use it in GitHub Desktop.
pubsub
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 eventsystem = (function (eventsystem) { | |
var topics = {}; | |
eventsystem = eventsystem || { | |
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) - 1; | |
// Provide handle back for removal of topic | |
return { | |
remove: function () { | |
delete topics[topic].queue[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; | |
items.forEach(function (item) { | |
item(info || {}); | |
}); | |
} | |
}; | |
return eventsystem; | |
})(eventsystem); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment