简体   繁体   中英

accessing variables from functions in javascript?

how can i access a variable that was intialsed in a function, but the main.name is giving me a null value, i know the value is initliased in the function, or on main, but not in the feed!! this is my example,

var main = Titanium.UI.createWindow();

var feed = Titanium.UI.createWindow({

    title:'feeds',
    url:'main_windows/feeds.js',
    barImage:'bg_content.gif',
    username:main.name //im trying too access this varibale from main.

});

Ti.App.addEventListener('grantEntrance',function(event)
{

    main.title ='Welcome'+event.username;
    main.url = 'main_windows/main.js';
    main.name = event.username; // this is where the varibale is intialised
    main.email = event.email;
    main.barImage='bg_content.gif';

});

sorry if this seems like a stupid question but im a newbie to javascript, so just tell me to delete it. i was wondering if you can turn it into a gloab or something.

You're trying to get variable that is not initialized yet. Since you're assigning main.name in a callback of event it will be initialized only after that event is fired. I'm not sure what's the logic of you'r application, but I guess you're able to initialize window inside this callback:

Ti.App.addEventListener('grantEntrance',function(event) {
    main.title ='Welcome'+event.username;
    main.url = 'main_windows/main.js';
    main.name = event.username;
    main.email = event.email;
    main.barImage='bg_content.gif';

    var feed = Titanium.UI.createWindow({
        title:'feeds',
        url:'main_windows/feeds.js',
        barImage:'bg_content.gif',
        username:main.name
    });
});

Or, just set username property of the window inside callback:

var feed = Titanium.UI.createWindow({
    title:'feeds',
    url:'main_windows/feeds.js',
    barImage:'bg_content.gif',
});

Ti.App.addEventListener('grantEntrance',function(event) {
    main.title ='Welcome'+event.username;
    main.url = 'main_windows/main.js';
    main.name = event.username;
    main.email = event.email;
    main.barImage='bg_content.gif';

    feed.username = main.name
});

Also, from personal experience: Titanium is not the best way to "fill the power" of js: some of methods are running asynchroniusly, and it causes weird issues. So if you're newbie it could be a pain in the ass..

Anyway good luck :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM