0

I have a JSON object that is returned inside a function (see below) and that in turn is inside a parent function and then a global function. There is a further child function within that global function that needs access to the JSON to parse the records.

I have left out some things that are not really part of the problem but hopefully included enough to explain the problem I have! You can see that

MyFunc.prototype.CreateMine = function(){
//do some work...
    submit: function(e,v,m,f){
        var xhr = new jsonRequest()
        xhr.onreadystatechange = function(){
            var jsonText = JSON.parse(xhr.responseText); //jsonText now contains my data
        };
    }
//need to access jsonText...
    }
}

Let me know if the example of not complete enough, thanks in advance Chris

cbm64
  • 1,059
  • 2
  • 12
  • 24
  • Why not just pass this `jsonText` variable _value_ to some external function - as a param? I mean something as simple as `someExternalFunc(jsonText);` – raina77ow Aug 21 '12 at 13:56

1 Answers1

0

Probably you should learn more about how scopes in JavaScript work. To put it simple, all variables created in the outer functions are available in the inner ones. So you just have to declare your jsonText in one of the "upper" functions.

Notice the absence of var in submit: this way it will try to find jsonText variable upper in the scope tree:

MyFunc.prototype.CreateMine = function(){
    var jsonText
    //do some work...
    submit: function(e,v,m,f){
        var xhr = new jsonRequest()
        xhr.onreadystatechange = function(){
            jsonText = JSON.parse(xhr.responseText); //jsonText now contains my data
        };
    }
    jsonText // available
    }
}

However, in your case a callback or a deferred would be better, because in submit jsonText is changed asynchronously, so you can't access it right after invoking submit.

function myCallback(myData) {
    // do smt with your data
}
MyFunc.prototype.CreateMine = function(){
    //do some work...
    submit: function(e,v,m,f){
        var xhr = new jsonRequest()
        xhr.onreadystatechange = function(){
            var jsonText = JSON.parse(xhr.responseText);
            myCallback(jsonText)
        };
    }
    }
}
Community
  • 1
  • 1
Georgii Ivankin
  • 2,702
  • 2
  • 23
  • 35
  • Hi, thanks for the quick response...I appreciate the comments. The first method did not work for me, but the second seems to, in that I can pass the contents of jsonText to the myCallback function, but I still cannot get that in the MyFunc function where I need it. Thanks for any further help! – cbm64 Aug 21 '12 at 14:04
  • oh, and in my example, the data in myCallback function is available as myData, not as jsonText – Georgii Ivankin Aug 21 '12 at 14:16
  • I can email it...it is quite big and relies on other objects. – cbm64 Aug 21 '12 at 14:17
  • well... so, do you have myData available inside myCallback function? – Georgii Ivankin Aug 21 '12 at 14:24