使用ko.utils.arrayForEach迭代observableArray

nth*_*apa 33 javascript knockout.js

我试图计算'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);

}());
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

RP *_*yer 60

在创建期间立即评估计算的可观察量.在您的情况下,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);
    
    Run Code Online (Sandbox Code Playgroud)
  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());?
    
    Run Code Online (Sandbox Code Playgroud)

  • 最后我使用(我完全不知道这是如何工作的)---`var self = this; $ .each(self.features(),function(){total + = this.price();});`但是使用ko.utils.arrayForEach仍然不起作用,感谢您的回复. (2认同)