2

I would like to know how the variable scope works when Ti.include.

I made application on titanium 2.*

var x = '12'

Ti.include('lib.js');

in lib.js

Ti.API.info(x) //it shows 12

However, now I am transferring this code into alloy

in app/controllers/index.js

var x = '12'

Ti.include('/mylib/lib.js');

in app/ssets/mylib/lib.js

app/ssets/mylib/lib.js // it says can't find variable x.

How can I make the global variable which is available in both file??

Nuno Macedo
  • 124
  • 5
whitebear
  • 11,200
  • 24
  • 114
  • 237

1 Answers1

3

If you need to assign global variable you can use Alloy.Globals object:

Alloy.Globals.myVar = 12;

Also instead of using Ti.include, it's much better to use require(); and convert your code to CommonJS module, so you will be able set which variable and functions you want to export:

/app/lib/util.js:

var privateValue = 'foo';

var publicValue = 'bar';

function getValues() {
    return [privateValue, publicValue];
}

module.exports = {
    publicValue: publicValue,
    getValues: getValues,
};

/app/controllers/index.js:

var util = require('/util');

Ti.App.info(util.privateValue); // undefined
Ti.App.info(util.publicValue); // 'bar'

util.publicValue = 'foobar';

Ti.App.info(util.getValues()); // [ 'foo', 'foobar' ];
technophyle
  • 7,972
  • 6
  • 29
  • 50
daniula
  • 6,898
  • 4
  • 32
  • 49
  • Thanks daniula I will use Alloy.Globals. for now. Then keep learning about 'lib' – whitebear Feb 25 '14 at 06:47
  • 1
    One caveat about global vars: Use them sparingly. Being global also means no garbage collection. EVERYTHING declared in `alloy.js` stays in memory for the duration of the app's lifecycle. Remember, just because you can doesn't mean you should. – Mike S. May 28 '14 at 12:47