Skip to content

Instantly share code, notes, and snippets.

@kyleburton
Created November 19, 2009 18:32
Show Gist options
  • Save kyleburton/238951 to your computer and use it in GitHub Desktop.
Save kyleburton/238951 to your computer and use it in GitHub Desktop.
/*
* Use to await multiple async ajax requests in a 'fire and forget' approach, with an even triggered
* on completion. We used this to hold back the display of a lightbox until the outstanding requests
* had fetched the data necessary for display - provided the user with a fully rendered lightbox, rather
* than a skeleton within which multiple elements then shifted around or popped in.
*
* $(document).bind('data.retrieved',showMyLightbox);
* multiGet('data.retrieved', {
* url: '/redata/us-states/',
* success: function(d) { populateSelectList('select#st',d); },
* error: showAsyncErrorResponse},
* {
* url: '/customer/address-info/',
* success: populateAddressDiv,
* error: showAsyncErrorResponse});
*/
Utils = {};
Util.argumentsToArray = function (args) {
var idx, ary = [];
for (idx = 0 ; idx < args.length; idx = idx + 1) {
ary[idx] = args[idx];
}
return ary;
};
Utils.ajax = function (opts) {
if ('POST' == opts.type || 'PUT' == opts.type) {
if (!opts.data || opts.data.length == 0) {
console.log('WARN: ajax request with no data: ' + opts.type + '; ' + opts.url);
}
}
var origErrorHandler = opts.error;
opts.error = function (request, textStatus, errorThrown) {
if (origErrorHandler) {
origErrorHandler.apply(this, arguments);
}
};
$.ajax(opts);
};
Utils.get = function (opts) {
Utils.ajax({
url: opts.url,
type: 'GET',
dataType: opts.dataType || 'json',
success: opts.success,
error: opts.error
});
};
Utils.multiGet = function () {
var args, doneEvent, countdownLatch, decrementLatch, buildCallback;
args = Utils.argumentsToArray(arguments);
doneEvent = args.shift();
countdownLatch = args.length;
decrementLatch = function () {
if ( 0 === --countdownLatch ) {
$(document).trigger(doneEvent);
}
};
buildCallback = function(eventName,callback) {
return function (data) {
if (eventName) {
$(document).trigger(eventName);
}
callback(data);
decrementLatch();
};
};
jQuery.each(args,function (idx, params) {
params.success = buildCallback(params.successEvent,params.success);
params.error = buildCallback(params.errorEvent,params.error);
Utils.get(params);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment