The electron documentation, provides the following code sample to create a new window:
const {BrowserWindow} = require('electron');
let win = new BrowserWindow({width: 800, height: 600});
win.on('closed', () => {
win = null
});
win.loadURL('https://github.com');
My question is: why set win to null at the close event?
N.B. The BrowserWindow class inherits from class EventEmitter.
I am not sure if this information is relevant, but I thought it might help to include it in the question.
Please give a detailed explanation with your answer.
Thanks in advance!
It's not mandatory, but a good coding practice (in every language).
Docs of 'closed' mentions it in a little bit more details:
After you have received this event you should remove the reference to
the window and avoid using it any more.
That is, when you destroy an object prefer setting it to an invalid value for avoiding function calls on a flawed/un-complete object.
Consider this example:
const {app, BrowserWindow} = require('electron')
let win = null
app.once('ready', () => {
win = new BrowserWindow()
win.on('closed', () => {
win = null
})
setInterval(() => {
if (win) win.loadURL('http://google.com')
else app.quit()
}, 3000)
app.on('window-all-closed', () => {})
})
The proper 'closed'
callback here helps to avoid future calls on destroyed object.
For electron's BrowserWindow
you can use isDestroyed()
method as well, which potentially makes the use of 'closed'
unnecessary but invalidating objects is a general technique while destroy queries are always up to the API.