Update exported property in nodejs

Asked

Viewed 36 times

0

I’m passing my app made in electronjs (nodejs) to the MVC standard and found 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 methods close(); and show(); in my windows, for they are given as undefined - which is perfectly logical, since it was the standard state I passed on to them.

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

1 answer

1


You could do it like 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 perhaps it would be better if you kept 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 the new BrowserWindow will be lost. If you use the loading-controller only once, that’s fine, but if one module uses one time, and another module then the two will be referencing the same window, and in that case the window created by the second call. The first window will remain in memory until it is closed.

If you’re wanting that window appear only once, it might be better to make this explicit in the code. For example, when calling createWindow, instantiate a new window only if loadingWindow === null.

  • I keep receiving as Undefined, Thiago :/ And how to keep the state to an instance of the module? Sorry, but I am layman and I started today with MVC and Nodejs standard.

  • Daniel, you changed at my suggestion in the two modules (controllers/loading-controller and controllers/main-controller)?

  • Now that I saw that I needed to match the exported window with the window that was running on Function, and it worked that is a beauty! Thank you, Thiago.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.