最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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('');

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!

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.');

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!

Share Improve this question asked May 25, 2018 at 7:41 MagedMaged 711 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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-plete 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.')
    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.

发布评论

评论列表(0)

  1. 暂无评论