如何从 Appcelerator 中的 commonJS 模块访问全局值? [英] How to access global value from commonJS module in Appcelerator?

查看:21
本文介绍了如何从 Appcelerator 中的 commonJS 模块访问全局值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很长时间以来,我通过创建可通过我加载的模块访问的全局变量来创建应用程序.

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();

通过调用 myApp.windows[windowName][functionName] 我可以从 commonJS 模块中操作其他窗口(例如更新列表).我也可以关闭,打开其他窗口

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

我发现从 commonJS 模块中调用全局变量不是一个好习惯(并且在通过推送打开应用程序时遇到了一些问题).

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

如果从 commonJS 模块加载窗口内容,访问其他窗口的最佳方法是什么?

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

推荐答案

IIRC,您访问全局变量的方式可能适用于 iOS,但不适用于 Android.你是对的,这不是一个好习惯.但是您可以将全局变量存储在模块中.

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.

创建一个模块 libs/Globals.js:

Create a module libs/Globals.js:

Globals = function () {};

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

现在在您的 app.js 中,您执行以下操作:

Now in your app.js, you do this:

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

任何时候您想从另一个 CommonJS 模块中引用这些窗口之一的实例,只需使用 Globals 模块:

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.

这篇关于如何从 Appcelerator 中的 commonJS 模块访问全局值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆