Skip to content

Instantly share code, notes, and snippets.

@lmartins
Created June 15, 2014 07:30
Show Gist options
  • Select an option

  • Save lmartins/62b9ec4ca46c69e778b6 to your computer and use it in GitHub Desktop.

Select an option

Save lmartins/62b9ec4ca46c69e778b6 to your computer and use it in GitHub Desktop.
Pub/Sub JavaScript Object http://davidwalsh.name/pubsub-javascript
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||{});
});
}
}
})();
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