1

I'm stuck on figuring out why function variables are empty after I receive result from another function.

Here I create a function (loader.js):

function Loader(){
    this.url = null;
    this.data = null;
    this.successCallback = null;
}

Loader.prototype.LoadData = function(){
    postAction(this.url, this.data, this.ResultCallback);
}

Loader.prototype.ResultCallback = function(result){

In this part I get this.successCallback as undefined same as the other variables in the function. It's like it's in the different scope.

    if(this.successCallback){ 
        this.successCallback(result)
    };
};

After I initialize it in other js part (other.js):

loader = new Loader();
loader.url = url;
loader.data = data;
loader.successCallback = function(result) { .. };
loader.LoadData();

What I'm trying to do is use one ajax method for all calls, where it process server side logic and if it's successful, then it can proceed and return result.

postAction (global.js):

function postAction(url, data, successCallback){
    $.ajax({
        type: 'POST'
        url: url,
        data: data,
        success: function(result){
            if(successCallback){
                successCallback(result);
            };
    });
};
chg
  • 114
  • 1
  • 7
  • you have to bind your `this.ResultCallback` when calling the `postAction` to `this`. Your current setup looks actually fine, except that you forgot the binding. The code, as you have it now will only handle best case scenarios though... Your analysis is however perfect, it is in a different scope :D – Icepickle Nov 14 '18 at 22:01
  • Why not just use `postAction(this.url, this.data, this.successCallback);`? – Bergi Nov 14 '18 at 22:16
  • Thanks @Icepickle for the quick answer as it answered my question. – chg Nov 14 '18 at 22:28
  • @Bergi successCallback can be null, it is required if there is somekind custom code required for the view it's being used for – chg Nov 14 '18 at 22:28
  • Then use `postAction(this.url, this.data, this.successCallback || function(){ … });` – Bergi Nov 14 '18 at 22:47

0 Answers0