jQuery xhrCache deferred
by southerd
HTML
<ul id="log"></ul>
JavaScript
function log(){
var msg = [].join.call(arguments, ': ')
$("#log").append($("<li></li>").text(msg));
}
(function($){
var cache_ = { body: "<h1>Header!</h1>" };
$.xhrCache = function(url) {
return cache_[url] ||
$.get(url)
.done(function(data){
cache_[url] = data;
});
};
$.xhrCache.printCache = function(){
$.each(cache_, function(k, v){log(k, v);});
};
})(jQuery);
log("Starting data");
$.xhrCache.printCache();
$.when($.xhrCache('body'), $.xhrCache('/echo/json'))
.then(function(){
log('Got data');
$.xhrCache.printCache();
}, function(errors){
log("There were errors:", errors);
});