「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);
}());
これを実行しようとすると、firebugコンソールで"エラー:this.featuresは関数ではありません"が表示されます。
何が間違っていますか?
計算されたオブザーバブルは、作成中にすぐに評価されます。あなたの場合、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());