This should be a very simple concept, but I just don’t understand. In a Titanium app I have an array of data used by several windows, my xhr result needs to be passed to the top level of my app’s namespace to be added to the array. I can successfully parse the JSON response inside of the onload function, but I want to separate my data code from my UI generation.
Here is a simplified app.js version so that I might be able to understand the concept. And no, I won’t pollute the global namespace in my real app.
Titanium.UI.setBackgroundColor('#000');
var myArray = [];
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
myArray = JSON.parse(this.responseText);
// var data = JSON.parse(this.responseText); // no help
// myArray.push(data); // no help
// return myArray; // no help
};
xhr.onerror = function() {
Titanium.UI.createAlertDialog({ message:"Something has gone terrible wrong."});
};
xhr.open('GET','http://myapp.com/data.json');
xhr.send();
var win = Ti.UI.createWindow();
var view = Titanium.UI.createView({
backgroundColor:'green'
});
var caption = myArray[2].caption;
var label = Ti.UI.createLabel({
color:'white',
text:caption,
textAlign:'center'
});
view.add(label);
win.add(view);
win.open();
Thanks for your patience!
Edit
This produces the the correct result from the user’s perspective, but I want to access the array outside the scope of the onload function. I don’t want to have UI code mixed with API calls.
xhr.onload = function() {
myArray = JSON.parse(this.responseText);
var caption = myArray[2].caption;
var label = Ti.UI.createLabel({
color:'white',
text:caption,
textAlign:'center'
});
view.add(label);
};
The code is being run asynchronously. The label is attempting to generate before the xhr.onload has begun.
you should fire an event from the onload method of your code.
the event will have a listener in the UI section of your application and it will provide the appropriate separation of http code from the ui code; Something like this
in your UI, view code
more on events from appcelerator documentation
and I have some examples on my blog, http://blog.clearlyinnovative.com, also