Created
March 29, 2012 08:49
-
-
Save sapegin/2235116 to your computer and use it in GitHub Desktop.
Caching Ajax requests with $.Deferred
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
var counters = { | |
promises: {}, | |
fetch: function(service, url) { | |
if (!counters.promises[service]) counters.promises[service] = {}; | |
var servicePromises = counters.promises[service]; | |
if (servicePromises[url]) { | |
return servicePromises[url]; | |
} | |
else { | |
var options = services[service], | |
deferred = $.Deferred(), | |
jsonUrl = options.counterUrl && options.counterUrl.replace('{PAGE_URL}', url); | |
if (typeof options.counter === 'function') { | |
options.counter(jsonUrl, deferred); | |
} | |
else if (options.counterUrl) { | |
$.getJSON(jsonUrl) | |
.done(function(data) { | |
try { | |
var number = data; | |
if (typeof options.convertNumber === 'function') { | |
number = options.convertNumber(data); | |
} | |
deferred.resolve(number); | |
} | |
catch (e) { | |
throw e; | |
deferred.reject(e); | |
} | |
}); | |
} | |
servicePromises[url] = deferred; | |
return deferred.promise(); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment