Update exported property on nodejs

0

I'm passing my electronjs app (nodejs) to the MVC standard and I encountered a problem when updating an exported property.

Example of my application.js :

// Importa os módulos privados
const config  = require('./config/config');
const loading = require('./controllers/loading-controller');
const main    = require('./controllers/main-controller');

app.on('ready', function () {
  loading.createWindow(__dirname);
  main.createWindow(__dirname);
  setTimeout(function(){ 
      loading.window.close();
      main.window.show();
  }, 3000);
});

Example of my loading-controller.js :

// Importa o model
const loading = require('../models/loading');

let loadingWindow;

module.exports = {
  createWindow: function (dir) {
    loadingWindow = new BrowserWindow(loading);
  },
  window: loadingWindow
}

The problem occurs when I try to execute the close(); and show(); methods in my windows, because they are given as undefined - which is perfectly logical since it was the default state I passed to them. p>

How do I update this property after running the function responsible for storing the BrowserWindow in it?

    
asked by anonymous 12.03.2018 / 09:15

1 answer

1

You could do this:

// Importa o model
const loading = require('../models/loading');

let loadingWindow;

const exported = {
  createWindow: function (dir) {
    exported.window = loadingWindow = new BrowserWindow(loading);
  },
  window: loadingWindow
};

module.exports = exported;

But you might want to keep this internal state to an instance of your module.

EDIT

To clarify my last comment. In your implementation, if you call createWindow more than once, the reference to new BrowserWindow will be lost. If you use the loading-controller only once, fine, but if one module uses one time, and then another module uses then both will be referencing the same window , in which case the window created by the second call. The first window will remain in memory until it is closed.

If you're wanting window to appear only once, you might want to make this explicit in your code. For example, when calling createWindow , instantiating a new window is only loadingWindow === null .

    
12.03.2018 / 09:21