问题描述
很长一段时间,我通过制作全局变量来创建应用程序,该变量是通过我加载的模块访问的.
var myApp = { windows: {} } myApp.windows.mainWindow = require('libs/pages/mainWindow').create(); myApp.windows.mainWindow.open();
通过调用myApp.windows[windowName][functionName],我可以从CommonJS模块中操作其他窗口(例如更新列表).我也可以关闭,打开其他窗口
我发现从CommonJS模块中调用全局变量不是好的做法(并且在从推动下打开了应用程序时经历了一些问题).
如果从CommonJS模块加载窗口内容,则访问其他窗口的最佳方法是什么?
推荐答案
iirc,您访问的方式可能在iOS上工作,但不是在Android上工作.你是对的,这不是良好的做法.但是您可以将全局变量存储在模块中.
创建模块libs/globals.js:
Globals = function () {}; Globals.windows = {}; module.exports = Globals;现在在您的App.js中,您这样做:
var G = require ('libs/Globals') G.windows.mainWindow = require('libs/pages/mainWindow').create();
您想要从另一个CommonJS模块中引用其中一个窗口之一的实例,只需使用全局模块:
var G = require ('libs/Globals') G.windows.mainWindow.close ();
在觉得你觉得你闭合并摧毁它们之后,请小心抓住对这些窗口的引用.如果在全局模块中将引用留给它们,则不会收集垃圾,并且您可以创建内存/资源泄漏.
问题描述
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?
推荐答案
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.