Global Variables
I am attempting to do a simple test of passing data and functions across windows.
In my app.js
I have
//Define Variables
var welcome;
a = 1;
function b()
{
return "hello";
}
function createElements()
{
welcome = Titanium.UI.createWindow(
{
url:'welcome.js',
backgroundImage:'form.png'
});
};
in welcome.js, how would I access variables or functions, I followed the example on the window api, but I keep getting undefined variables in window.js.
window.js
var win = Titanium.UI.currentWindow;
welcome.a = a;
welcome.b = b;
alert("b() = "+Titanium.UI.currentWindow.b());
3 Answers
-
Accepted Answer
MB, Something is not right in your code:
in app.js, to assign values to variables you want to pass to another window
function createElements() { welcome = Titanium.UI.createWindow( { url:'welcome.js', backgroundImage:'form.png' a = 1; //your custom field }); };
in window.js or welcome.js, to access those values
var win = Titanium.UI.currentWindow; Ti.API.info(win.a) alert(win.a)
You can also look at the Kitchen Sink example. Try 'custom_properties.js' to see how you can send/retrieve variables between windows.
-
The correct syntax in the app.js example above would be:
welcome = Ti.UI.createWindow({ url: 'welcome.js', backgroundImage: 'form.png', a: 1, foobar: 'my custom field' }); //add another custom field welcome.newfield = 23.3;
Then you can just access win.a, win.foobar, and win.newfield in welcome.js (per your example).
-
Hi there,
If you attach variables to windows, you'll need to keep a close eye on where the user may go and 'pass-the-parcel' around at each stage. I recommend putting your global variables into 'properties', which you can retrieve from any context. These are persistent, so you may need to 'initialise' properties when your app starts.
For functions have you thought about having a specific JS file for common functions, which you can 'include' any appropriate window js file.
cheers,
Chris.