How to access global value from commonJS module in Appcelerator?

陌路散爱 提交于 2019-12-12 04:47:17

问题


For long time I was creating apps by making global variable which was accessible via modules I load.

var myApp = {
   windows: {}
}

myApp.windows.mainWindow = require('libs/pages/mainWindow').create();

myApp.windows.mainWindow.open();

By calling myApp.windows[windowName][functionName] I could manipulate other windows (for example update lists) from within the commonJS module. I could also close, open other windows

I found that calling global variables from within commonJS module is not good practice (and experienced some issues when app was opened from push).

What is the best approach to access other windows if window content is loaded from commonJS module?


回答1:


IIRC, the way you are accessing globals might work on iOS, but not on Android. You're right, it's not good practice. But you can store global variables in a module.

Create a module libs/Globals.js:

Globals = function () {};

Globals.windows = {};
module.exports = Globals;

Now in your app.js, you do this:

var G = require ('libs/Globals')
G.windows.mainWindow = require('libs/pages/mainWindow').create();

Any time you want to reference an instance of one of these windows from inside another CommonJS module, just use the Globals module:

var G = require ('libs/Globals')
G.windows.mainWindow.close ();

Be careful about holding onto references to these windows after you think you've closed and destroyed them. If you leave references to them in the global module, they won't get garbage collected, and you could create memory/resource leaks.



来源:https://stackoverflow.com/questions/43805905/how-to-access-global-value-from-commonjs-module-in-appcelerator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!