私は '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);
}());
これを実行しようとすると、「エラー: this.features は関数ではありません」Firebug コンソールで。
何が間違っているのでしょうか?
ベストアンサー1
計算された観測可能値は、作成時にすぐに評価されます。この場合、 はappViewModel
まだ作成されていないため、this
を表しませんappViewModel
。
this
この場合、正しいことを確認する方法はたくさんあります。ここでは 2 つを紹介します。
最初のオブジェクトリテラルの外側に作成します。
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);
関数内でビュー モデルを作成します。
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());