Question

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??

Was it helpful?

Solution

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' ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top