Как вставить экземпляр класса в закрытый массив другого класса? - PullRequest
0 голосов
/ 22 сентября 2018

У меня есть класс, как показано ниже:

class RoomUsageList {

constructor()
{
    // private atributes
    this._roomList = [];

}

set roomList(newIns)
{
    this._roomList.push(newIns);
}
}

И файл функции (в другом файле javascript), который передает набор другого класса (RoomUsage) в установщик класса RoomUsageList (выше)) как показано ниже:

function saveTap()
{
// create a new class instance when the SAVE button
// is pushed.
let newAddress = document.getElementById('address').value;
let newRoomNo = document.getElementById('roomNumber').value;
let newLightSwitch = document.getElementById('lights').checked;
let newHeatCoolSwitch = document.getElementById('heatingCooling').checked;
let newSeatsUsed = document.getElementById('seatsUsed').value;
let newSeatsTotal = document.getElementById('seatsTotal').value;


let roomUsageIns = new RoomUsage();
roomUsageIns.address = newAddress;
roomUsageIns.roomNumber = newRoomNo;
roomUsageIns.lightsOn = newLightSwitch;
roomUsageIns.heatingCoolingOn = newHeatCoolSwitch;
roomUsageIns.seatsTotal = newSeatsTotal;
roomUsageIns.seatsUsed = newSeatsUsed;

// add the above-created class instance into the RoomUsageList class

let roomUsageList = new RoomUsageList(roomUsageIns);
roomUsageList.roomList = roomUsageIns;

console.log(roomUsageList);

}

Вывод содержит только один экземпляр и не выдвигает новые экземпляры RoomUsage.Почему это так?Я новичок в программировании, любая помощь будет удивительной!

ВЫХОД:

enter image description here

Ответы [ 3 ]

0 голосов
/ 22 сентября 2018

Спасибо за вашу помощь, благодаря небольшой корректировке кода программа работает отлично.Вот что я сделал:

//Room Usage List Class
//---------------------
//
class RoomUsageList {

constructor()
{
    // private atributes
    this._roomList = [];

}

set roomList(newIns)
{
    // pushes new array into parent class instance
    this._roomList.push(newIns);
}  
}

//making the parent class instance global
const roomUsageList = new RoomUsageList();

function saveTap()
{
// create a new class instance when the SAVE button
// is pushed.
let newAddress = document.getElementById('address').value;
let newRoomNo = document.getElementById('roomNumber').value;
let newLightSwitch = document.getElementById('lights').checked;
let newHeatCoolSwitch = document.getElementById('heatingCooling').checked;
let newSeatsUsed = document.getElementById('seatsUsed').value;
let newSeatsTotal = document.getElementById('seatsTotal').value;

let roomUsageIns = new RoomUsage();
roomUsageIns.address = newAddress;
roomUsageIns.roomNumber = newRoomNo;
roomUsageIns.lightsOn = newLightSwitch;
roomUsageIns.heatingCoolingOn = newHeatCoolSwitch;
roomUsageIns.seatsTotal = newSeatsTotal;
roomUsageIns.seatsUsed = newSeatsUsed;

// add the above created class instance into the RoomUsageList class
roomUsageList.roomList = roomUsageIns;
console.log(roomUsageList);

}
0 голосов
/ 22 сентября 2018

Вы должны использовать setter только для установки всего списка, а не для добавления элементов - для этого вы можете создавать отдельные методы, например addItem для добавления одного элемента или addItems, который вставляет более одного целого числа в массив

class RoomUsageList {

  constructor() {
    this._roomList = [];
  }

  set roomList(roomList) {
    this._roomList = roomList;
  }

  addItem(item) {
    this._roomList.push(item);
  }

  addItems(items) {
    this._roomList.concat(items);
  }
}

Хорошо, что вы нашли решение - с каждым вызовом функции создается новый экземпляр:)

0 голосов
/ 22 сентября 2018

Проблема в том, что вы создаете новый экземпляр RoomUsageList каждый раз, когда вызывается функция saveTap.Это сбрасывает _roomList в [].

Если вы вызываете roomUsageList = new RoomUsageList() вне функции, тогда установщик должен работать как положено и добавлять новые экземпляры RoomUsage к частному атрибуту _roomList.

РЕДАКТИРОВАТЬ: Typo EDIT2: Удалены дополнительные журналы консоли в фрагмент кода

class RoomUsage {
  constructor () {
    //
  }  
}

class RoomUsageList {
  constructor () {
    // private attributes
    this._roomList = [];
  }

  set roomList(newIns) {
    const roomList = [...this._roomList, newIns];
    this._roomList = roomList
  }
}

// Create global state
const roomUsageList = new RoomUsageList();

function onFormSubmit (event) {
  event.preventDefault();

  // create a new class instance when the SAVE button
  // is pushed.
  let newAddress = document.querySelector('.address').value;
  let newRoomNo = document.querySelector('.roomNumber').value;
  let newLightSwitch = document.querySelector('.lights').checked;
  let newHeatCoolSwitch = document.querySelector('.heatingCooling').checked;
  let newSeatsUsed = document.querySelector('.seatsUsed').value;
  let newSeatsTotal = document.querySelector('.seatsTotal').value;

  let roomUsageIns = new RoomUsage();
  roomUsageIns.address = newAddress;
  roomUsageIns.roomNumber = newRoomNo;
  roomUsageIns.lightsOn = newLightSwitch;
  roomUsageIns.heatingCoolingOn = newHeatCoolSwitch;
  roomUsageIns.seatsTotal = newSeatsTotal;
  roomUsageIns.seatsUsed = newSeatsUsed;

  // add the above-created class instance into the RoomUsageList class
  
  roomUsageList.roomList = roomUsageIns;

  console.log(roomUsageList);
}
<form onsubmit="onFormSubmit(event)">
  
  <div>
    <label>Address</label>
    <input type="text" class="address">    
  </div>

  <div>
    <label>Room Number</label>
    <input type="text" class="roomNumber">    
  </div>

  <div>    
    <label>Lights</label>
    <input type="text" class="lights">
  </div>

  <div>    
    <label>
      <input type="checkbox" class="heatingCooling">
      Heating/Cooling
    </label>
  </div>

  <div>    
    <label>Seats Used</label>
    <input type="text" class="seatsUsed">
  </div>

  <div>    
    <label>Seats Total</label>
    <input type="text" class="seatsTotal">
  </div>

  <button type="submit">Save</button>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...