Is this correct or other advice?

You must Login before you can answer or comment on any questions.

App type: Mobile will run on Android&ios.

As u know, using "require" is recommended by Titanium. Can I use a shared js file which will be required by every other files?

Etc. I write some common functions and variables in common.js, and "require('common')" in other js file, to make the common functions and variables to be global vars.

if it's ok, there is any problems with memory? Or the common functions and variable maybe lost at some time. if not, any advice please.

Sorry to my poor english, but please give some suggestions. I think not only me, many developers want to know about this.

— asked 10 months ago by li xinxin
0 Comments

2 Answers

Accepted Answer

This is exactly the reason for commonJS. You can require it as often as you need, Ti will cache the Module, so you get a Kind of singleton.

— answered 10 months ago by Alexander Bauer
answer permalink
3 Comments
  • Ti will cache the Module. this means cache will be cleared in cases?

    Such as click home button(Android), when i came back, the cached functions/variables will be reserved yet?

    I know when memory is not enough, the background app will be killed by mobile os, if the cached contents' life cycle is the same as the app?

    thanks a lot.

    — commented 10 months ago by li xinxin

  • Caching means in this context, its the same for the lifetime of the app. Once the app is killed, requires certainly needs to pull it again into the memory.

    If you want to have some sort of app settings, then you gotta go with Ti.App.properties. They will be saved until the app is deinstalled. Using properties you could instantiate a commonJS module with your vars.

    — commented 10 months ago by Alexander Bauer

  • ok, thank u very much.

    — commented 10 months ago by li xinxin

You will not be able to maintain global state. The 'global' object you get from requiring a file is a new one each time. Somebody please correct me if I am wrong.

My solution is to pass my global object as a parameter to required files:

var thing = require('some_other_thing).(GlobalVar, opts)

— answered 10 months ago by Esben Maaløe
answer permalink
3 Comments
  • Thats wrong, its the same object. As I said, its being cached.

    — commented 10 months ago by Alexander Bauer

  • Thanks, I'll check that out!

    — commented 10 months ago by Esben Maaløe

  • Yup - that's wrong and you are right

    thanks again!

    — commented 10 months ago by Esben Maaløe

Your Answer

This question has been locked and cannot accept new answers.