Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Promise callback with Parameters

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.

like image 623
Spencer Mark Avatar asked Sep 11 '26 19:09

Spencer Mark


2 Answers

There's no need to supply additional closures - the lines below should work fine:

thisPromise.done(thisCallback);
thisPromise.fail(formObject.topError.bind(formObject));

The done callback will be passed the data, textStatus, jqXHR parameters as supplied by $.ajax. This line is just registering the supplied callback function directly.

The fail callback will similarly get the right parameters, except that I've used .bind here to ensure that this is correctly set to the formObject. 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.

like image 92
Alnitak Avatar answered Sep 13 '26 08:09

Alnitak


Use closures:

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(function(data, textStatus, jqXHR) {
                 thisCallback(/* additional parameters*/)
        });
..........................
    }
};
like image 41
Sergii Stotskyi Avatar answered Sep 13 '26 08:09

Sergii Stotskyi