I’m trying to figure out how I could pass the parameters to the callback function triggered by jQuery’s promise object. My method, which calls the ajax and then the promise methods looks like this:
var formObject = {
call : function(thisForm, thisUrl, thisArray, thisCallback) {
"use strict";
var thisMethod = thisForm.attr('method').toUpperCase();
var thisPromise = $.ajax({
type : thisMethod,
url : thisUrl,
dataType : 'json',
data : thisArray,
cache : false
});
thisPromise.done(thisCallback(data, textStatus, jqXHR));
thisPromise.fail(formObject.topError(jqXHR, textStatus, errorThrown));
}
};
The parameters in done() and fail() methods are incorrect – but this is exactly what I’m trying to figure out.
There’s no need to supply additional closures – the lines below should work fine:
The
donecallback will be passed thedata, textStatus, jqXHRparameters as supplied by$.ajax. This line is just registering the supplied callback function directly.The
failcallback will similarly get the right parameters, except that I’ve used.bindhere to ensure thatthisis correctly set to theformObject. If this code is to be used on pre-ES5 browsers, just install a shim for.bind– there’s one on the Mozilla site linked above.