从 Electron 函数传回数据

Passing back data from Electron function

我正在打开 Electron 打开对话框:

var electron = require('electron');
const {dialog} = electron.remote;

var browsedFile = dialog.showOpenDialog({properties: ['openFile' ], filters: [{name: 'Scripts', extensions: ['sh']}]} );

我有像这样声明的 Electron 函数

function readFileAsString(filePath, functionCallback) {

  var fs = require('fs');
  fs.readFile(filePath, 'utf8', function (err, data) {
    functionCallback(err, data);
  });

}

exports.readFileAsString = readFileAsString;

然后调用Electron函数,传入一个回调函数

var openScriptFile = electron.remote.require('./main.desktop').readFileAsString;
openScriptFile(filePath, this.afterOpenScriptFileCallback);

在回调函数中,我试图通过 this.myVar 访问组件中的变量,但它们未定义,可能超出范围?

afterOpenScriptFileCallback(err, data) {
    if(err){
      console.log('error opening file: ', err);
    } else {
      this.myVar = data;
    }
}

如何从 Electron 的回调中访问 this.myVar 变量?

首先去掉 electron.remote.require,很少有实际有意义的情况,只需使用常规 require

那么您可能需要进行以下更改:

openScriptFile(filePath, this.afterOpenScriptFileCallback.bind(this))

我建议您通读 How does the "this" keyword work? 以了解这里发生了什么。