【问题标题】:Knockout Computed sum of Nested list嵌套列表的计算总和
【发布时间】:2013-08-12 13:38:26
【问题描述】:

我正在尝试计算嵌套子列表的值的总和,我要查询的 VM 正在使用 KO 映射器进行映射,然后使用我的计算字段进行扩展。它似乎找不到我要查找的嵌套数组:

var HouseholdViewModel = function(data) {
    this.$type = 'HouseholdViewModel';
    ko.mapping.fromJS(data, mapping, this);

    this.T12 = ko.computed(function () {
        var total = 0;
        ko.utils.arrayForEach(this.Accounts(), function (account) {
            total += account.T12Revenue();
        });
        return total;
    }, this);

};

var AccountViewModel = function(data) {
    this.$type = 'AccountViewModel';
    ko.mapping.fromJS(data, mapping, this);
};

var mapping = {
    'Households': {
        create: function(options) {
            return new HouseholdViewModel(options.data);
        }
    },
    'Accounts': {
        create: function(options) {
            return new AccountViewModel(options.data);
        }
    }
};

我收到错误消息“Uncaught TypeError: Object [object Object] has no method 'Accounts'”。我假设这是由于 KO.Mapper 尚未绑定 Accounts 但映射调用高于计算的 observable。任何帮助将不胜感激。

【问题讨论】:

  • 提示:将<pre data-bind="text: ko.toJSON($root, null, 2)"></pre> 添加到您的页面并检查您的视图模型。

标签: jquery knockout.js knockout-mapping-plugin


【解决方案1】:

解决此问题的一个简单方法是在尝试在计算中使用它之前确保您有帐户。当 Accounts 存在时,这将通知您计算重新计算 -

var HouseholdViewModel = function(data) {
    this.$type = 'HouseholdViewModel';
    ko.mapping.fromJS(data, mapping, this);

    this.T12 = ko.computed(function () {
        var total = 0;
        if (!this.Accounts) { return 0; }
        ko.utils.arrayForEach(this.Accounts(), function (account) {
            total += account.T12Revenue();
        });
        return total;
    }, this);
};

如果 this.Accounts 不存在,则在其中添加 if 语句以不返回任何内容(或任何您想要的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多