Last active
January 3, 2016 17:09
-
-
Save paul-bjorkstrand/8494277 to your computer and use it in GitHub Desktop.
Global ajax management
This file contains 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
/* | |
* 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; | |
}; | |
})($); |
This file contains 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
/* | |
* 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