0

Given a pretty big Knockout.js ViewModel filled with observables, and corresponding input fields on the View:

var PersonViewModel = {
  var name = ko.observable();
  var age = ko.observable();
  // and so on...
}

Say I've got an observable array filled with people objects (i.e. ko.toJS(PersonViewModel)), which generates a list of people on the View. For any person in the list, I want users to be able to click on a person to edit their information, and for the person object in the observable array to be overwritten.

Aside from manually updating all of the input fields, how could I use PersonViewModel to pull up a specific person's information in the input fields?

Can this be done by updating the properties of the ViewModel after bindings are applied / can mappable objects be passed back to the ViewModel? Could I use jQuery's $.map() to map a person object back onto the ViewModel without any consequences, or would this make the ViewModel no longer observable?

alex
  • 6,818
  • 9
  • 52
  • 103

1 Answers1

0

Well, I figured out a way to get this working. If the Javascript object looks something like:

var specificPerson = {name: "John", age: 30, etc: "etc..."}

and given that the Knockout.JS observable can only be set via:

PersonViewModel.name('Jane');

Then you can iterate through a specific person's properties, temporarily store the values, and apply them to the ViewModel:

for (var property in specificPerson) {
   var value = specificPerson[property];
   PersonViewModel[property](value);
};

In this way, the specific person's properties will appear in the input fields bound to the ViewModel.

Community
  • 1
  • 1
alex
  • 6,818
  • 9
  • 52
  • 103