使用Knockout.js是否可以创建计算数组?

4
我有一个使用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类中添加一个计算可观察属性呢? - Chris Moutray
1
@ChrisMoutray 这也是一种可能性。根据我拥有的数据,我可以按照您建议的方式进行操作。但问题仍然存在,是否可能创建计算数组。 - Konstantin Dinev
1个回答

11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接