Skip to content

How to create global variables in Titanium

The first and obvious way to create a global variable is to initialize it straight from the root in app.js. The usual

var myGlobalVar1 = 'this';

when it is placed out of any brackets.
I actually saw a seemingly official sample application with a comment in app.js saying something along the lines “define your global variables here”. It seems like it should work great, and for me it did… until I implemented notifications using gcm.js.
For some reason, when a gcm.js notification is clicked to open the application, if the application wasn’t already running in the background it will crash because all global variables defined in app.js will be defined locally only (see for instance this post on Appcelerator Q&A). I’m not sure what happens, but my best bet is that somehow gcm.js or the functions it uses launch app.js as some kind of local object, so whatever is defined in it in this context is local and not global as expected.

Anyway, so I needed a more reliable way to create a global variable.
A number of options are suggested in the following posts:

Some involve adding includes at the beginning of every file, and then I wonder how a modification from one view might modify the value in another one. The method I found the most convincing is to attach your wanted global variable to an already existing, guaranteed global variable, for instance Ti.App. Apparently this isn’t a “recommended” way, but it’s a natural feature of JavaScript so should be fairly future-proof.

So, instead of

var myGlobalVar1 = 'this';

we’ll now use

Ti.App.myGlobalVar1 = 'this';

and voilà. The only problem now is that you variable names are quite longer. Personally I even use

Ti.App.myappGlobal.myGlobalVar1 = 'this';

so that if by any chance Titanium decides to rename Ti.App I won’t have any issue to automatically replace all “Ti.App.myappGlobal” with something else.

Update (2014-12-16): sadly, apparently this trick doesn’t work to create global functions on iOS… FFFS

Update (2014-12-23): I finally found a workaround: if variables and/or functions are created in a separate file, which is then included into app.js using Ti.include(), then they are properly registered as global. The big problem with this solution is that Ti.include was deprecated in Titanium 3.3.0 so I’m afraid it might get removed in a not too distant future :s

Posted in programming.

Tagged with .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA