2013-07-15 44 views
0

我有可讀寫的總計算輸入框。計算寫入不適用於陣列

<div data-bind="foreach:TotalCostQuantity"> 
    <input data-bind:"value: Cost, valueUpdate:'afterkeydown'" /><br /> 
    <input data-bind:"value: Quantity, valueUpdate:'afterkeydown'" /> 
</div> 

我的視圖模型是這樣的:

self.TrancheCostQuantity = ko.computed({ 
     read: function() { 
      //do some math here to calculate cost and quant totals 

      return [{Cost:100, Quantity:10},{Cost:200, Quantity:20}]; 
     }, 
     write: function (newValue) { 
      customformat(newValue); 
     } 
    }, self); 

的成本和數量都從能有行和列的動態數量的網格。它使用ko.mapping插件進行映射。

我需要寫入,但它從來沒有。閱讀工作正常,但我無法驗證或自定義格式我的寫道。

+1

你能不能做一個小提琴? – Damien

+1

'customformat'函數的作用是什麼? –

+0

customformat將使TrancheCostQuantity向上舍入到最近的美元並添加一個美元符號。 – user1175857

回答

1

首先要做的事情是:當你發佈例子時你應該更加小心。請確保他們的工作:

  • 在你TotalCostQuantity的HTML,但在視圖模型:TrancheCostQuantity
  • 在您使用data-bind:"value...的HTML,但是這應該是data-bind="value...

與問題可計算的觀察值是您在編輯值時更改包含的值,但不是數組本身,因此從不調用write函數。 (這是除了事實,即使knockoutjs這樣工作,它不會工作,因爲CostQuantity屬性不是可觀察的)。

A工作液:http://jsfiddle.net/P2Zqm/

var CostQuantity = function(cost, quantity) { 
    self = this; 

    self.Cost = ko.observable(cost); 
    self.Quantity = ko.observable(quantity); 

    self.CustomFormat = ko.computed(function() { 
     return parseInt(this.Cost(),10) * parseInt(this.Quantity(),10); 
    }, self); 
}; 

var vm = function() { 
    self = this; 
    self.TotalCostQuantity = ko.computed(function() { 
     //do some math here to calculate cost and quant totals 

     return [new CostQuantity(100,10), new CostQuantity(200,20)]; 
    }); 
}; 

ko.applyBindings(new vm()); 
+0

是的!優秀的答案。就像OP一樣,當'寫'永遠不會被觸發時,我過度複雜了我的代碼。 –