Skip to content

Instantly share code, notes, and snippets.

@alexbaulch
Created December 11, 2014 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbaulch/74b36415f7b9a0ba3402 to your computer and use it in GitHub Desktop.
Save alexbaulch/74b36415f7b9a0ba3402 to your computer and use it in GitHub Desktop.
Miniature PubSub library in AMD pattern
define(function() {
'use strict';
var pubSub = function pubSubFn() {
var topics = {};
function subscribe(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];
}
};
}
function publish(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 {
subscribe: subscribe,
publish: publish
};
};
return pubSub();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment