从Electron函数传回数据

时间:2016-12-15 01:22:17

标签: javascript angular typescript electron

我打开Electron打开对话框:

for f in *.txt; do
    printf "%s: %s\n" "$f" "$(xxd -l 3 "$f")"
done >> log

我将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;

在回调函数中,我试图通过var openScriptFile = electron.remote.require('./main.desktop').readFileAsString; openScriptFile(filePath, this.afterOpenScriptFileCallback); 访问组件中的变量,但它们是未定义的,可能超出范围?

this.myVar

如何从Electron回调中访问afterOpenScriptFileCallback(err, data) { if(err){ console.log('error opening file: ', err); } else { this.myVar = data; } } 个变量?

1 个答案:

答案 0 :(得分:1)

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

然后您可能需要进行此更改:

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

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