-
-
Save fomigo/1852853 to your computer and use it in GitHub Desktop.
jQuery ajax grouping with Deferred objects.
This file contains hidden or 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
(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