[英]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.