Невозможно получить доступ к новому заданному значению из области ipcRenderer - электрон javascript - PullRequest
0 голосов
/ 26 февраля 2020

Я пытаюсь обновить значение переменной в моем вызове ipcRenderer.on ('Отправка профиля назад', функция (..) ..), но моя переменная не обновляется до нового значения, когда я вызываю его за пределами сфера В моей консоли я получаю неопределенное значение для переменной profileChosen, но внутри функции ipcRenderer я получаю правильные значения profileChosen. profileChosen - это класс Profile.

основной процессор


const electron = require('electron');
const {app, BrowserWindow, Menu,MenuItem,ipcMain} = electron;
const url = require('url');
const path = require('path'); //might not need this
const menu = new Menu();

let mainWindow;
let profilesArray = [];

class Profile{
    constructor(firstname,lastname,address1,address2,zipcode,city,country,state,profileName){
        this.firstname = firstname;
        this.lastname = lastname;
        this.address1 = address1;
        this.address2 = address2;
        this.zipcode = zipcode;
        this.city = city;
        this.country = country;
        this.state = state;
        this.profileName = profileName;
    }

}


//Creates our mainwindow for the app
app.on('ready',function() {
    mainWindow = new BrowserWindow({
        width: 1280,
        height: 720,
        webPreferences: {
            nodeIntegration: true // need this for higher electron versions
        }
    });

    //will link it with mainWindow.html to catch/send events
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname,'mainWindow.html'),
        protocol: 'file:',
        slashes: true
    }));

    //closes the app when you press the close button on upper right corner
    mainWindow.on('closed', () => {
        profilesArray = null;
        app.quit();
    });
});

/** When the save profile button is pressed from mainWindow.html we will execute this **/
ipcMain.on('save new profile',function(event,newProfile){
    console.log('hello from save new profile ipcMain');

    profilesArray.push(newProfile);

});

ipcMain.on('Request profile',function(event,profileNameRequest){
        let selectedProfile;
        console.log('in request profile ' + profileNameRequest);
        console.log(profilesArray.length);
outerforloop:for(let i = 0;i < profilesArray.length;i++){

                if(profilesArray[i].profileName == profileNameRequest){
                    selectedProfile = profilesArray[i];
                    console.log('Found requested profile');
                    break outerforloop;
                }
            }

        mainWindow.webContents.send('Sending profile back',selectedProfile);
});

процессор рендеринга, в котором возникает ошибка в функции saveTask ()

window.onload = function(){ //need to include this if we use this externally from mainWindow.html


  const electron = require('electron');
  const {ipcRenderer} = electron;


  document.getElementById('NewProfileButton').addEventListener('click',clearTextFields);
  document.getElementById('SaveProfileButton').addEventListener('click',saveProfile);
  document.getElementById('SaveTaskButton').addEventListener('click',saveTask);


  function clearTextFields(){
  let tabPanes = document.querySelectorAll("div.tabcontent");
  let deleteTexts = tabPanes[0].querySelectorAll("input"); //gets the profile text pane's input elements

  /** Gets each text field in the profile tab and sets the values to '' **/
  deleteTexts.forEach(function(textField){
      textField.value = '';
      console.log("hi");
  });
  }

  /** Used for the saveProfile function. **/
  class Profile{
  constructor(firstname,lastname,address1,address2,zipcode,city,country,state,profileName){
      this.firstname = firstname;
      this.lastname = lastname;
      this.address1 = address1;
      this.address2 = address2;
      this.zipcode = zipcode;
      this.city = city;
      this.country = country;
      this.state = state;
      this.profileName = profileName;
  }
  }

  class Task{
      constructor(websiteChosen,typeOfTask,LKV,Size,ProfileChosen,NumOfTasks,Quantity,ProxyListChosen,UserName,Password){
          this.websiteChosen = websiteChosen;
          this.typeOfTask = typeOfTask;
          this.LKV = LKV;
          this.Size = Size;
          this.ProfileChosen = ProfileChosen;
          this.NumOfTasks = NumOfTasks;
          this.Quantity = Quantity;
          this.ProxyListChosen = ProxyListChosen;
          this.UserName = UserName;
          this.Password = Password;
      }
  }


  function saveProfile(){
      let firstName = document.getElementById("firstNameTextFieldShip").value;
      let lastName = document.getElementById("lastNameTextFieldShip").value;
      let address1 = document.getElementById("Address1TextFieldShip").value;
      let address2 = document.getElementById("Address2TextFieldShip").value;
      let zipcode = document.getElementById("ZipTextFieldShip").value;
      let city = document.getElementById("CityTextFieldShip").value;
      let selectedValueForCountry = document.getElementById("CountriesSelectShip");

      //this will get the selected value for country
      let country = selectedValueForCountry.options[selectedValueForCountry.selectedIndex].text;
      let state = document.getElementById("StateTextFieldShip").value;
      let profileName = document.getElementById("ProfileNameTextField").value;
      let newProfile = new Profile(firstName,lastName,address1,address2,zipcode,city,country,state,profileName);

      ipcRenderer.send('save new profile', newProfile);
      //we'll get the correct profile through profile name
      let addOntoProfilesSelect = document.getElementById('ProfileChosen');

      let addOption = document.createElement('option');
      addOption.value = newProfile.profileName;
      addOption.innerHTML = newProfile.profileName;

      console.log(document.getElementById("ProfileNameTextField"));
      addOntoProfilesSelect.appendChild(addOption);

      console.log(addOntoProfilesSelect);
  }

  function saveTask(){
      let selectedWebsiteChosen = document.getElementById("WebsiteChosen");
      let websiteChosen = selectedWebsiteChosen.options[selectedWebsiteChosen.selectedIndex].text;

      let selectedTypeOfTask = document.getElementById("TypeOfTask");
      let typeOfTask = selectedTypeOfTask.options[selectedTypeOfTask.selectedIndex].text;

      let LKV = document.getElementById("LKVTextField").value;

      let selectedSize = document.getElementById("SizeChosen");
      let Size = selectedSize.options[selectedSize.selectedIndex].text;

      let selectedProfile = document.getElementById("ProfileChosen");
      let profileName = selectedProfile.options[selectedProfile.selectedIndex].text;

      //var profileChosen;

      let userName = document.getElementById("UserName").value;
      let password = document.getElementById("Password").value;
      let numOfTasks = document.getElementById("NumOfTasksTextField").value;
      let Quantity = document.getElementById("QuantityTextField").value;
      let selectedProxyList = document.getElementById("ProxiesListChosen");
      **var profileChosen;
      ipcRenderer.send('Request profile',profileName);
      ipcRenderer.on('Sending profile back',function(event,arg){
          console.log(arg);
          profileChosen = arg;
          console.log(profileChosen); //prints out the correct profileChosen
      });
      console.log(profileChosen); //prints out undefined**

      let newTask = new Task(websiteChosen,typeOfTask,LKV,Size,profileChosen,numOfTasks,Quantity,
                             null,userName,password);

      addOntoDashboard(newTask);



      //let proxyListName = selectedProxyList.options[selectedProxyList.selectedIndex].text;

      //let proxyList; for now we'll comment this out 




  }

  function addOntoDashboard(newTask){
      let dashboardDiv = document.getElementById('DashboardTab');
      let newDiv;
      let label = document.createElement('label');
      console.log(newTask.websiteChosen);
      for(let i = 0;i < newTask.NumOfTasks;i++){
          newDiv = document.createElement('div');
          newDiv.className = 'block';

          label.innerHTML = newTask.websiteChosen;
          newDiv.appendChild(label);
          label.innerHTML = newTask.LKV;
          newDiv.appendChild(label);
          label.innerHTML = newTask.Size;
          newDiv.appendChild(label);
          label.innerHTML = newTask.profileChosen.profileName;
          newDiv.appendChild(label);
          label.innerHTML = newTask.Quantity;
          newDiv.appendChild(label);
          label.innerHTML = newTask.proxyListName;
          newDiv.appendChild(label);
          console.log(newDiv);
          dashboardDiv.appendChild(newDiv);
      }

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