Skip to content

Instantly share code, notes, and snippets.

@fomigo
Forked from Zoramite/jquery.groupedAjax.js
Created February 17, 2012 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fomigo/1852853 to your computer and use it in GitHub Desktop.
Save fomigo/1852853 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