Created
June 15, 2014 07:30
-
-
Save lmartins/62b9ec4ca46c69e778b6 to your computer and use it in GitHub Desktop.
Pub/Sub JavaScript Object
http://davidwalsh.name/pubsub-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
| module.exports = (function() { | |
| "use strict"; | |
| 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 the queue | |
| var index = topics[topic].queue.push(listener) - 1; | |
| // Provide handle back for removal of topic | |
| return (function (topic, index) { | |
| return { | |
| remove: function () { | |
| delete topics[topic].queue[index]; | |
| } | |
| } | |
| })(topic, 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||{}); | |
| }); | |
| } | |
| } | |
| })(); |
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 events = require('./pubsub'); | |
| (function() { | |
| "use strict"; | |
| var App = { | |
| Events: events, | |
| init: function () { | |
| // Pusblish Events | |
| App.Events.publish('/page/load', { | |
| url: '/some/url/path', | |
| }); | |
| // Subscribe Events | |
| App.Events.subscribe('/page/load', function () { | |
| console.log("Event Page/Load detected and triggered event in FeatureA module"); | |
| }); | |
| } | |
| }; | |
| window.App = App; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment