使用ko.utils.arrayForEach对observableArray进行迭代

Using ko.utils.arrayForEach to iterate over a observableArray

本文关键字:迭代 observableArray ko utils arrayForEach 使用      更新时间:2023-09-26

我正在尝试计算"observableArray"的"price"字段的和。到目前为止,我有以下代码:

(function(){
function objFeatures(name,price) {
        return {
            name: ko.observable(name),
            price: ko.observable(price),
            removeFeatures: function () {
                appViewModel.features.remove(this);
            }
        }
    }
var appViewModel = {
features: ko.observableArray([
            new objFeatures("Feature1", 20),
            new objFeatures("Feature2", 20)
        ]),
 grandTotal: ko.computed(function () {
            var total = 0;
            ko.utils.arrayForEach(this.features(), function () {
                total += this.price();
            })
            return total;
        })
};
ko.applyBindings(appViewModel);
}());

当我尝试运行这个时,我在firebug控制台中得到一个"错误:this.features不是函数"

我做错了什么?

在创建过程中会立即评估计算的可观察性。在您的情况下,appViewModel尚未创建,this将不代表appViewModel

在这种情况下,有很多方法可以确保this是正确的。这里有两个:

  1. 在初始对象文字之外创建它:

    var appViewModel = {
       features: ko.observableArray([
           new objFeatures("Feature1", 20),
           new objFeatures("Feature2", 20)
           ])
    };
    appViewModel.grandTotal = ko.computed(function() {
        var total = 0;
        ko.utils.arrayForEach(this.features(), function(feature) {
            total += feature.price();
        });
        return total;
    }, appViewModel);
    
  2. 在函数中创建视图模型:

    var AppViewModel = function() {
        this.features = ko.observableArray([
            new objFeatures("Feature1", 20),
            new objFeatures("Feature2", 20)
        ]);
        this.grandTotal = ko.computed(function() {
            var total = 0;
            ko.utils.arrayForEach(this.features(), function(feature) {
                total += feature.price();
            });
            return total;
        }, this);
    };
    ko.applyBindings(new AppViewModel());​