NodeJS:无法读取未定义的属性“hide”

时间:2018-05-15 04:07:17

标签: javascript node.js oop scope electron

问题

我正在使用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

关闭窗口或单击托盘图标时发生错误。那是onCloseonClick触发时,this.mainWindowthis.isQuitting undefined

的时间

如果您想了解更多信息,请与我们联系。

任何想法或建议都表示赞赏:)

1 个答案:

答案 0 :(得分:1)

您正在传递this.onClose,但您可能正在丢失对this的引用。

this.mainWindow.on('close', this.onClose.bind(this));

应该修理它。