ScottN
ScottN

Reputation: 1528

Passing back data from Electron function

I'm opening the Electron open dialog:

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

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

I have the Electron function declared like

function readFileAsString(filePath, functionCallback) {

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

}

exports.readFileAsString = readFileAsString;

Then I'm calling the Electron function, passing in a callback function

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

Inside the callback function, I'm trying to access variables in the component via this.myVar, but they're undefined, presumably out of scope?

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

How do I access this.myVar variables from inside the callback from Electron?

Upvotes: 0

Views: 198

Answers (1)

Vadim Macagon
Vadim Macagon

Reputation: 14847

First get rid of the electron.remote.require, there are very few cases where that actually makes sense, just use regular require.

Then you probably need to make this change:

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

I suggest you read through How does the "this" keyword work? to understand what's going on here.

Upvotes: 1

Related Questions