How to can I create an array of knockout.js observ

2019-08-18 08:30发布

问题:

I have an array of objects for which I am showing their properties. How can add an individual edit functionality to them? Lets say it to be an edit button for each one of the elements of the list.

I want to show input fields instead of text fields when the object is in edit mode, for this I am using the visible binding. So I need a Boolean observable for each of them.

How can I do this without knowing the amount of elements in the list... I also have add and delete, so I would need to add more observables to this array each time a new element is created.

I also tried to give a ko.observable element to my objects but I could not do this.

回答1:

I like to use an object inside the observableArray. Here is an example of an inline edit feature for as many many rows as needed.

function Employee(emp) {
  var self = this;
  self.Name = ko.observable(emp.Name);
  self.Age = ko.observable(emp.Age);
  self.Salary = ko.observable(emp.Salary);
  self.EditMode = ko.observable(emp.EditMode);
  self.ChangeMode = function() {
    self.EditMode(!self.EditMode());
  }
}

function viewModel() {
  var self = this;
  self.Employees = ko.observableArray()
  self.Employees.push(new Employee({
    Name: "Joe",
    Age: 20,
    Salary: 100,
    EditMode: false
  }));

  self.Employees.push(new Employee({
    Name: "Steve",
    Age: 22,
    Salary: 121,
    EditMode: false
  }));

  self.Employees.push(new Employee({
    Name: "Tom",
    Age: 24,
    Salary: 110,
    EditMode: false
  }));
}
var VM = new viewModel();
ko.applyBindings(VM);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table border=1>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Salary</th>
      <th></th>
    </tr>
  </thead>
  <tbody data-bind="foreach: Employees">
    <tr data-bind="if: !EditMode()">
      <td data-bind="text: Name"></td>
      <td data-bind="text: Age"></td>
      <td data-bind="text: Salary"></td>
      <td><button data-bind="click: ChangeMode">Edit</button></td>
    </tr>
    <tr data-bind="if: EditMode()">
      <td>
        <input data-bind="value: Name">
      </td>
      <td>
        <input data-bind="value: Age">
      </td>
      <td>
        <input data-bind="value: Salary">
      </td>
      <td><button data-bind="click:ChangeMode">Save</button></td>
    </tr>
  </tbody>
</table>