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;
}
var listOfPeople = [
new Person(1, 'Fred', 25),
new Person(2, 'Joe', 60),
new Person(3, 'Sally', 43)
];
var viewModel = {
this.people = ko.observableArray(listOfPeople);
this.selectedPeople = ko.observableArray([]);
}
I would like to build a list of checkboxes, one for each person, something along these lines:
<ul data-bind="foreach: people">
<li>
<input type="checkbox" data-bind="value: id, checked: ?">
<span data-bind="name"></span>
</li>
</ul>
My confusion is that in the checkbox data-bind
attribute, I would like to refer to both the object being selected (that is, the person
or the person's id
), as well as to the list of all selected people. How do I refer to that in the scope of the foreach
binding?
I guess a corollary is: how do I refer to the object being bound? Here "this
" seemed to be bound to the window, not to the object.
The example of the "checked
binding on the knockoutjs site" deals with primitives and uses a named template. I am confused about how to do this with objects and with anonymous templates.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…