ko.utils.arrayForEach を使用して observableArray を反復処理する 質問する

ko.utils.arrayForEach を使用して observableArray を反復処理する 質問する

私は '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 つを紹介します。

  1. 最初のオブジェクトリテラルの外側に作成します。

    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);
    
  2. 関数内でビュー モデルを作成します。

    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());​
    

おすすめ記事