In my application i'm isolating the networking in a method and performing a callback to get the JSON response , how can i use it afterward ?
getJson(url, acallback);
function getJson(url, callback) {
Ti.API.info(" im here " + url);
var jsonObject;
var xhr = Ti.Network.createHTTPClient();
xhr.setTimeout(3000);
xhr.onload = function () {
var jsonObject = eval('(' + this.responseText + ')');
callback.call(jsonObject)
}
xhr.open("GET", url);
xhr.send();
Ti.API.info(" passed ");
};
function acallback() {
return this;
}
Now my questions is , how can i use the returned output afterward ?
Should look like this:
Notice that I removed the use of eval since it's bad practice to use that, as it says (here):
Also, you better use the var keyword only once per scope.
Edit
If you want to use the resulting json object from outside the scope of the callback, just define the callback in the scope where the json is needed, for example:
The json.y part I just made up for the example of course.
2nd Edit
Alternatively, if you want to use the call option, you can do this:
3rd Edit
If we're on the subject, I recommend using a nice trick, which is used in Prototype, MooTools, jQuery and according to the MDN was Introduced in JavaScript 1.8.5.
You can read the tutorial where I copied to code from.
I believe
callback.call(jsonObject)
should actually readcallback(jsonObject)
. Once you have invoked an asynchronous function, the way to get its value is via a callback. So, the function you pass in ascallback
will get the result. Say,The code that needs to use the output should be placed in
acallback
(or placed in a function that's called fromacallback
).