使用 ko.utils.arrayForEach 迭代 observableArray
我正在尝试计算“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 不是函数”。
我做错了什么?
I am trying to calculate sum of 'price' field of an 'observableArray'. I have the following code so far:
(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);
}());
When I try to run this, i get an "Error: this.features is not a function" in the firebug console.
What am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
计算的可观察量在创建期间立即评估。在您的情况下,
appViewModel
尚未创建,this
将不代表appViewModel
。在这种情况下,有很多方法可以确保
this
是正确的。这里有两个:在初始对象文字之外创建它:
在函数中创建视图模型:
Computed observables are evaluated immediately during creation. In your case,
appViewModel
has not been created yet andthis
will not represent theappViewModel
.There are many ways to ensure that
this
is correct in this case. Here are two:Create it outside of your initial object literal:
Create your view model in a function: