Skip to content

Instantly share code, notes, and snippets.

@jaubourg
Created February 14, 2012 22:09
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 jaubourg/fd91392798a0f0f6d053 to your computer and use it in GitHub Desktop.
Save jaubourg/fd91392798a0f0f6d053 to your computer and use it in GitHub Desktop.
(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
// Note the use of the returned promise
getData({
bar: 'foo'
}).done(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();
// Or if you only want results and no ajax thingy
// requests[ hash ] = $.getJSON( "/some/path", query ).pipe(function( results ) { return results; });
}
return requests[hash].done( callback );
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment