web-dev-qa-db-ja.com

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

}());

これを実行しようとすると、firebugコンソールで"エラー:this.featuresは関数ではありません"が表示されます。

何が間違っていますか?

33
nthapa

計算されたオブザーバブルは、作成中にすぐに評価されます。あなたの場合、appViewModelはまだ作成されておらず、thisappViewModelを表しません。

この場合、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());​
    
60
RP Niemeyer