【发布时间】:2018-05-15 04:07:16
【问题描述】:
问题
我正在使用 Electron 和 Node,并且遇到了变量 (this.mainWindow) 只能在创建它的函数内部访问的问题。每当事件侦听器触发时,this.mainWindow 是未定义的。这一切都发生在一个类内部,所以this 应该是对该类的工作实例的引用,对吗?
代码
class AppManager {
constructor (app, options) {
this.app = app
this.options = options = {}
this.bindEvents()
}
bindEvents () {
this.app.on('ready', this.onReady.bind(this))
this.app.on('window-all-closed', this.onWindowAllClosed.bind(this))
this.app.on('activate', this.onActivate.bind(this))
}
onReady () {
this.createWindow()
}
onWindowAllClosed () {
if (process.platform !== 'darwin') {
this.app.quit()
}
}
onActivate () {
if (this.app.mainWindow === null) {
this.createWindow()
}
}
onClose (e) {
// here, this.mainWindow and this.isQuitting are undefined.
if (this.isQuiting) {
this.mainWindow = null
} else {
e.preventDefault()
this.mainWindow.hide()
}
}
onClick () {
// here, this.mainWindow is undefined.
this.mainWindow.show()
}
createWindow () {
// here, we declare this.isQuitting
this.isQuitting = false
this.contextMenu = Menu.buildFromTemplate([
{
label: 'Show App',
click: function () {
this.mainWindow.show()
}
},
{
label: 'Quit',
click: function () {
this.isQuiting = true
this.app.quit()
}
}
])
this.tray = new Tray('./public/images/icon.ico')
this.tray.setContextMenu(this.contextMenu)
this.tray.on('click', this.onClick)
// at this point, we assign the variable mainWindow to "this".
this.mainWindow = new BrowserWindow(this.options)
this.mainWindow.loadURL(url.format({
pathname: path.join(__dirname, '../../../public/index.html'),
protocol: 'file:',
slashes: true
}))
this.mainWindow.tray = this.tray
this.mainWindow.on('close', this.onClose)
}
}
错误
A JavaScript error occurred in the main process
Uncaught exception: TypeError: cannot read property hide of undefined
当我关闭窗口或单击托盘图标时发生错误。那是onClose 和onClick 着火的时候,那是this.mainWindow 和this.isQuitting 是undefined 的时候
如果您想了解更多信息,请告诉我。
任何想法或建议表示赞赏:)
【问题讨论】:
标签: javascript node.js oop scope electron