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

查看:110
本文介绍了如何从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模块中调用全局变量不是一个好习惯(当通过push打开应用程序时遇到了一些问题).

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天全站免登陆