I have a list of objects, each with a few fields, like this:
function Person(id,name,age) {
this.id = id;
this.name = name;
this.age = age;
}
va
You can do something like:
<ul data-bind="foreach: people">
<li>
<input type="checkbox"
data-bind="checkedValue: id, checked: $parent.selectedPeople">
</li>
</ul>
With this kind of ViewModel:
var viewModel = {
people: ko.observableArray(listOfPeople),
selectedPeople: ko.observableArray()
};
The value attribute controls what the checked binding adds/removes from an array when it is bound against an array. You could also write a dependentObservable that populates the array with the actual objects, if necessary.
Live Example:
function Person(id,name,age) {
this.id = id;
this.name = name;
this.age = age;
}
var listOfPeople = [
new Person(1, 'Fred', 25),
new Person(2, 'Joe', 60),
new Person(3, 'Sally', 43)
];
var viewModel = {
people: ko.observableArray(listOfPeople),
selectedPeople: ko.observableArray([1])
};
ko.applyBindings(viewModel);
<ul data-bind="foreach: people">
<li>
<input type="checkbox" value="" data-bind="checkedValue: id, checked: $parent.selectedPeople"><span data-bind="text: name"></span>
</li>
</ul>
<hr/>
<div data-bind="text: ko.toJSON($root)"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>