Skip to content

Instantly share code, notes, and snippets.

@paul-bjorkstrand
Last active January 3, 2016 17:09
Show Gist options
  • Save paul-bjorkstrand/8494277 to your computer and use it in GitHub Desktop.
Save paul-bjorkstrand/8494277 to your computer and use it in GitHub Desktop.
Global ajax management
/*
* Requires a minimal change to the $.ajax calls, adding:
* globalAjax: true
* globalAjax: {
* name: "" // optional
* usePostData: true // optional
* }
* As long as the globalAjax object is "truthy", it will store the response,
* at bare minimum using options.type + "|" + options.url as the key
*/
(function($) {
"use strict";
var XHRs = {};
$.ajaxTransport("json", function(options, originalOptions, jqXHR) {
if (options.globalAjax) {
var data = options.type === "POST" && !!options.globalAjax.usePostData && "|" + options.data || "",
name = (options.globalAjax.name || options.type + "|" + options.url) + data;
var xhr = XHRs[name];
if (xhr) {
return {
send: function(_, done) {
xhr.then(function(_, __, storedXHR) {
done(storedXHR.status, storedXHR.statusText, { text: storedXHR.responseText }, storedXHR.getAllResponseHeaders());
}, function(storedXHR, _, __) {
done(storedXHR.status, storedXHR.statusText, { text: storedXHR.responseText }, storedXHR.getAllResponseHeaders());
});
},
abort: $.noop
};
} else {
XHRs[name] = jqXHR;
}
}
});
$.listGlobalAjax = function() {
return XHRs;
};
})($);
/*
* Requires a call to special $.globalAjax, possibly requires some refactoring of existing code.
*/
(function($) {
"use strict";
var deferreds = {};
function isAjaxCall(a, b) {
return (a && typeof a !== "function");
}
$.globalAjax = function(name, urlOrResolved, optionsOrRejected) {
var deferred = deferreds[name] || (deferreds[name] = $.Deferred());
if (!isAjaxCall(urlOrResolved, optionsOrRejected)) {
deferred.then(urlOrResolved, optionsOrRejected);
} else {
$.ajax(urlOrResolved, optionsOrRejected).then(function(data, textStatus, jqXHR) {
deferred.resolve(data, textStatus, jqXHR);
}, function(jqXHR, textStatus, errorThrown) {
deferred.reject(data, textStatus, errorThrown);
});
}
return deferred.promise();
};
})($);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment