我正在尝试计算“observableArray”的“价格”字段的总和。到目前为止,我有以下代码:
(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 不是一个函数”。
我做错了什么?
最佳答案
Computed observables 在创建期间立即进行评估。在您的情况下,appViewModel
尚未创建,this
将不代表 appViewModel
。
有很多方法可以确保 this
在这种情况下是正确的。这里有两个:
在初始对象文字之外创建它:
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);
在函数中创建 View 模型:
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());
关于javascript - 使用 ko.utils.arrayForEach 迭代一个 observableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9351939/