Created
December 11, 2014 16:42
-
-
Save alexbaulch/74b36415f7b9a0ba3402 to your computer and use it in GitHub Desktop.
Miniature PubSub library in AMD pattern
This file contains 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
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