Android cannot find my global variable within a commonjs module
To organize my project better, I made a global object that contains settings/global functions/etc. and I included that in my app.js file.
global_var.js
var GlobalVar = {};
GlobalVar.font = 'foo';
GlobalVar.bar = function() {return true;}
Then in app.js I include this file.
Ti.include('global_var.js');
I then create a commonjs module for a window and in that I reference the GlobalVar variable.
menu.js
... code to create window ...
var label = Ti.UI.createLabel({
text : 'Foo Label',
font : {
fontFamily : GlobalVar.font,
fontSize : 24
});
Everything works great in iOS, but when I try to run on the Android emulator I get an error for "Uncaught ReferenceError: GlobalVar is not defined". Why can Android not see the global variable?
Titanium SDK 1.8, Android 2.2.3 V8
4 Answers
-
Accepted Answer
To copy-paste myself :)
In Titanium's CommonJS implementation, variables defined in global scope cannot be referenced from module's scope.
That is, CommonJS module creates new JS context (like iframe in browser environment), so even if you do something like change of native prototypes like "String.prototype" (String.prototype.doSomething = function() {}), that won't be reflected in module scope (typeof "".doSomething === "undefined").
Now, is that a good thing or a bad thing can be discussed. :) -
On Android you cannot have variables outside the current commonJS scope. From what I understand, the behaviour you are seeing is actually an 'error' in the iOS javascript implementation (at least that's what I read on the boards in a previous post).
-
a solution can be found at www.thewarpedcoder.net shows how to create a global variable module.
Hope this helps.
T…
-
Well, good to know it's not possible then.
What is a good way to try to achieve global variables between multiple modules? I might just drop commonjs because it has caused me more problems than benefits.