NickD
NickD

Reputation: 2646

Extend Callback with parameters

Assuming I have a method wrapping the jQuery ajax method:

function GetJson(url, completeCallback, alwaysCallback, failCallback) {   
var newUrl = location.protocol + "//" + location.host + url;

$.getJSON(newUrl).done(function (result) {
    if (typeof completeCallback == "function") {
        completeCallback(result);
    }                
}).fail(function (jqxhr, textStatus, error) {
    if (typeof failCallback == "function") {
        failCallback(result);
    } else {
        alert("Request failed for " + url + " textStatus:" + textStatus + " Error:" + error);
    }        
}).always(function () {
    if (typeof alwaysCallback == "function") {
        alwaysCallback();
    }        
}); }

And i call the DoSomething method, which internally calls GetJson. The result from the GetJSON callback I want to pass as the first parameter of DoResume; the remaining arguments should be passed from the methods signature.

function DoSomething(a, b, c, id) {
var url = '/MyController/GetData?id=' + id;    
GetJson(url, DoResume(this.Result, a, b, c)); }

function DoResume(result, a, b, c) { }

I tried to achieve this using this keyword, but the result is not assigned.

Upvotes: 0

Views: 321

Answers (2)

AaronK
AaronK

Reputation: 21

In your example, you are not passing DoResume into SendJSON, you're calling DoResume, then passing its result. You need to pass a function instead.

SendJSON( url, null, function( result ) {
    DoResume( result, a, b, c );
} );

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to pass a function not the result of its invocation

GetJson(url, function(result){
    DoResume(result, a, b, c);
});

Upvotes: 3

Related Questions