Electron - Why set BrowserWindow instance to null on the close event

心已入冬 提交于 2019-12-11 18:22:11

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/50523957/electron-why-set-browserwindow-instance-to-null-on-the-close-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!