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在这种情况下,有很多方法可以确保这是正确的.这是两个:
在初始对象文字之外创建它:
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)在函数中创建视图模型:
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)| 归档时间: |
|
| 查看次数: |
86194 次 |
| 最近记录: |