[英]Is it possible to create computed arrays with Knockout.js
我有一个带有可观察数组的基因敲除ViewModel
:
function ItemsViewModel() {
this.data = ko.observableArray([
new Item(1, "One description"),
new Item(2, "Two description"),
new Item(3, "Three description"),
// ... etc
]);
}
该项目看起来像这样:
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
};
基于我在ViewModel
创建的可观察数组,我想创建另一个计算数组,如下所示:
function ItemsViewModel() {
this.data = ko.observableArray([
new Item(1, "One description"),
new Item(2, "Two description"),
new Item(3, "Three description"),
// ... etc
]);
this.computedData = // here I want to create a computed array based on the values
// of this.data
}
我似乎无法在knockout.js文档中的任何地方找到如何创建此计算数组的示例。 您能否举一个例子,说明如何将第一个数组转换为以下形式的计算数组:
this.computedData = [
{ dataItem: data[0].name + ' ' + data[0].id },
{ dataItem: data[1].name + ' ' + data[1].id },
// ... etc.
]
您可以为此使用computed
观察值:
self.computedData = ko.computed(function() {
return ko.utils.arrayMap(self.data(), function(item) {
return { dataItem: item.name() + ' ' + item.id() };
});
});
这是工作示例: http : //jsfiddle.net/vyshniakov/3fesA/1/
阅读文档中有关计算的更多信息: http : //knockoutjs.com/documentation/computedObservables.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.