NodeJS: невозможно прочитать свойство 'hide' из неопределенного - PullRequest
0 голосов
/ 15 мая 2018

Проблема

Я работаю с 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

Дайте мне знать, если вам нужна дополнительная информация.

Любые мысли или предложения приветствуются:)

1 Ответ

0 голосов
/ 15 мая 2018

вы передаете this.onClose, но вы, вероятно, теряете ссылку на this.

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

Должно это исправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...