将对象列表绑定到复选框列表
我有一个对象列表,每个对象都有几个字段,如下所示:
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([]);
}
我想构建一个复选框列表,每个人一个,沿着这些思路:
<ul data-bind="foreach: people">
<li>
<input type="checkbox" data-bind="value: id, checked: ?">
<span data-bind="name"></span>
</li>
</ul>
我的困惑是在复选框 data-bind< /code> 属性,我想引用所选择的对象(即
person
或该人的 id
),以及所有列表选定的人。我如何在 foreach
绑定的范围内引用它?
我猜一个推论是:我如何引用被绑定的对象?这里的“this
”似乎绑定到窗口,而不是对象。
“knockoutjs 网站上的checked
绑定”示例处理原语并使用命名模板。我对如何使用对象和匿名模板执行此操作感到困惑。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行以下操作:
对于这种 ViewModel:
value
属性控制在绑定数组时checked
绑定在数组中添加/删除的内容。如果需要,您还可以编写一个 dependentObservable,用实际对象填充数组。实例:
You can do something like:
With this kind of ViewModel:
The
value
attribute controls what thechecked
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: