电子-为什么在关闭事件上将BrowserWindow实例设置为null [英] Electron - Why set BrowserWindow instance to null on the close event

查看:223
本文介绍了电子-为什么在关闭事件上将BrowserWindow实例设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

电子文档,提供了以下代码示例来创建新窗口:

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

我的问题是:为什么在比赛结束时将胜利设置为null?

My question is: why set win to null at the close event?

NB BrowserWindow 类是从 EventEmitter 继承的。
我不确定此信息是否相关,但我认为将其包含在问题中可能会有所帮助。

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.

预先感谢!

推荐答案

这不是强制性的,但良好的编码习惯(用每种语言)。

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', () => {})
})

此处正确的'closed'回调有助于避免将来调用销毁的对象。

The proper 'closed' callback here helps to avoid future calls on destroyed object.

对于电子 BrowserWindow ,您也可以使用 isDestroyed()方法,这可能使使用'closed'是不必要的,但是使对象无效是一种通用技术,而销毁查询始终取决于API。

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.

这篇关于电子-为什么在关闭事件上将BrowserWindow实例设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆