我有一些包含父项的数据,以及每个父项的子项。我尝试为每个父项渲染子项的计数,如果子项被删除,则计数会更新。
JS:
var viewModel = ko.mapping.fromJS({
items: [
{title: 'red', subItems: [ {subTitle: '1'}, {subTitle: '2'} ] },
{title: 'blue', subItems: []},
{title: 'green', subItems: []}
]
});
viewModel.countSubItems = function(itemIndex) {
return viewModel.items()[itemIndex].subItems().length;
};
ko.applyBindings(viewModel);
HTML:
<!-- ko foreach: items -->
<div>
<span data-bind="text: title"></span> has <span data-bind="text: viewModel.countSubItems($index)"></span> sub items
</div>
<!-- /ko -->
我得到的东西是viewModel.items(itemIndex)的效果是未定义的。我是否需要以某种方式将函数与可计算结合起来?现场示例(可编辑):http://jsbin.com/bonez/1/edit
答案 0 :(得分:0)
您需要将ko.computed包装成函数并将该函数传递给itemIndex
viewModel.countSubItems = function(itemIndex)
{
return ko.computed(function(){
return viewModel.items()[itemIndex()].subItems().length;
});
};
答案 1 :(得分:0)
一种简单的方法是使用计算机扩展项目映射。在此示例中,每个父项都将具有一个名为“countSubItems”的计算器。
JS:
var itemViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.countSubItems = ko.computed(function() {
return self.subItems().length;
}, self);
};
var viewModel = ko.mapping.fromJS({
items: [
{title: 'red',subItems: [ {subTitle: '1'},{subTitle: '2'} ] },
{title: 'blue',subItems: []},
{title: 'green',subItems: []}
]
}, {'items':{create: function (options) {return new itemViewModel(options.data);}}});
ko.applyBindings(viewModel);
HTML:
<!-- ko foreach: items -->
<div>
<span data-bind="text: title"></span> has <span data-bind="text: countSubItems"></span> sub items
</div>
<!-- /ko -->