NickD NickD - 4 months ago 17
Javascript Question

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.

Answer

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

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