Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

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());
— asked June 22nd 2010 by M B
  • globals
  • iphone
  • mobile
  • windows
0 Comments

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.

    — answered June 23rd 2010 by Johnny Basu
    permalink
    0 Comments
  • 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).

    — answered June 23rd 2010 by Richard Baughman
    permalink
    0 Comments
  • 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.

    — answered June 23rd 2010 by Chris Reed
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.