Skip to content Skip to sidebar Skip to footer

How To Can I Create An Array Of Knockout.js Observables?

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 eleme

Solution 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.

functionEmployee(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());
  }
}

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

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

  self.Employees.push(newEmployee({
    Name: "Tom",
    Age: 24,
    Salary: 110,
    EditMode: false
  }));
}
varVM = newviewModel();
ko.applyBindings(VM);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><tableborder=1><thead><tr><th>Name</th><th>Age</th><th>Salary</th><th></th></tr></thead><tbodydata-bind="foreach: Employees"><trdata-bind="if: !EditMode()"><tddata-bind="text: Name"></td><tddata-bind="text: Age"></td><tddata-bind="text: Salary"></td><td><buttondata-bind="click: ChangeMode">Edit</button></td></tr><trdata-bind="if: EditMode()"><td><inputdata-bind="value: Name"></td><td><inputdata-bind="value: Age"></td><td><inputdata-bind="value: Salary"></td><td><buttondata-bind="click:ChangeMode">Save</button></td></tr></tbody></table>

Post a Comment for "How To Can I Create An Array Of Knockout.js Observables?"