Skip to content

Instantly share code, notes, and snippets.

@Zoramite
Created February 14, 2012 21:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Zoramite/1830528 to your computer and use it in GitHub Desktop.
Save Zoramite/1830528 to your computer and use it in GitHub Desktop.
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