【问题标题】:Is it possible to create computed arrays with Knockout.js是否可以使用 Knockout.js 创建计算数组
【发布时间】: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 这也是一种可能性。使用我拥有的数据,我可以按照您的建议进行操作。问题仍然在于是否可以创建计算数组。

标签: javascript knockout.js


【解决方案1】:

您可以为此使用computed observable:

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

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2023-03-05
    • 2020-06-06
    • 2015-07-21
    相关资源
    最近更新 更多