2012-02-19 97 views
31

我試圖計算一個'observableArray'的'價格'字段的總和。我有以下代碼至今:使用ko.utils.arrayForEach遍歷一個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); 

}()); 

當我嘗試運行此,我得到一個「錯誤:this.features不是一個函數」在Firebug控制檯

我在做什麼錯了?

回答

55

計算的可觀測量在創建過程中立即進行評估。在你的情況下,appViewModel尚未創建,this將不代表appViewModel

有很多方法可以確保this在這種情況下是正確的。這裏有兩個:

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

我去與第一方法,現在我不能訪問'this.price()' – nthapa13 2012-02-19 19:05:06

+2

最後我用(我絕對不知道這是如何工作的)---'var self = this; (self.features(),function(){ total + = this.price(); });'但是使用ko.utils.arrayForEach仍然不起作用,不過謝謝你的回覆。 – nthapa13 2012-02-19 19:17:58

+1

@ Nthapa13我沒有注意到你在那部分使用的語法。我更新了上面的答案,以顯示您在'ko.utils.arrayForEach'中指定的函數接收該項目作爲其第一個參數,那麼您不需要在函數中使用'this'。 – 2012-02-19 20:48:39