I have read a bunch on closures, and for the most part understand the basic concept. That said, can someone explain the following snippet of code as far as where the closures are created and what the difference between returning a function and returning an object.
return function () {
var topics = {};
return {
subscribe: function (topic, listener) {
if (listener && typeof (listener) === 'function') {
topics[topic] = topics[topic] || { queue: [] };
}
var index = topics[topic].queue.push(listener) - 1;
return (function (topic, index) {
return {
remove: function () {
delete topics[topic].queue[index];
}
}
})(topic, index);
},
publish: function (topic, info) {
if (!topics[topic] || !topics[topic].queue.length) return;
angular.forEach(topics[topic].queue, function (listener) {
listener.apply(this, info);
});
}
};
};