Create a gist now

Instantly share code, notes, and snippets.

jQuery ajax grouping with Deferred objects.
(function($){
var requests = {};
$(function(){
// Determine which data you need and call the getData()...
// Stubbing in some example data...
// This is a unique request and would make an ajax call
getData({
foo: 'bar'
}, function(results){
console.log('Results:', results);
});
// This is a unique request and would make an ajax call
getData({
bar: 'foo'
}, function(results){
console.log('Results:', results);
});
// This is a duplicate request and would wait for the original call to finish
getData({
foo: 'bar'
}, function(results){
console.log('Results:', results);
});
// Above would have generated two AJAX requests...
});
function getData(query, callback) {
query = query || {};
// Create a repeatable, unique key for the request
hash = MD5(JSON.stringify(query));
if(!requests[hash]) {
requests[hash] = $.getJSON( "/some/path", query ).promise();
}
return requests[hash].done(callback);
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment