Let's say I have a $.Deferred
and a jqXHR
object. Is there a way to transfer all the handlers bound to the deferred (then, always, done, fail) over to the XHR object (which, as I understand it, is an extension of Deferred)?
Here's what I had in mind:
$.ajaxOne = function(options) {
var xhr = null;
return function() {
if(xhr) xhr.abort();
xhr = $.ajax(options).always(function() {
xhr = null;
});
}
}
I wanted to create a function, similar to $.ajax
, except that if you call it multiple times in rapid succession, it will abort the last request and only complete the most recent one. This is useful in many scenarios where you want to validate a user's input.
For example, you might want to check if a username is taken, but if they start typing in the username field again after you've started your ajax call, you don't care about the last result, only the most recent one.
Also, I don't think requests are guaranteed to return in the same order they went out (I suppose depending on your server setup), so you could have a syncing issue as well.
Anyway, the problem with the above code is that because it returns a function, you can execute your ajax call whenever you like, but you can't bind your completion handlers to it. So I have to somehow mix the deferred handlers in and rebind them to the XHR object.