How to access global value from commonJS module in

2019-09-17 11:10发布

问题:

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.