【发布时间】:2012-11-28 13:11:04
【问题描述】:
我有一个带有可观察数组的 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.
]
【问题讨论】:
-
你为什么不简单地在你的 Item 类中添加一个计算出来的 observable?
-
@ChrisMoutray 这也是一种可能性。使用我拥有的数据,我可以按照您的建议进行操作。问题仍然在于是否可以创建计算数组。