2015-10-20 88 views
-1

如何將行添加到Knockout.js中的可編輯表格中?如何在Knockout.js中追加映射的可觀察數組?

var data = { 
    "Lines": [ 
     {"Entries": [{"Hours": 5.5},{"Hours": 2.50},{"Hours": 3.75}]}, 
     {"Entries": [{"Hours": 5.1},{"Hours": 2.00},{"Hours": 4.75}]}, 
     {"Entries": [{"Hours": 1.2},{"Hours": 3.00},{"Hours": 2.12}]} 
    ] 
} 
var data1 = {"Entries": [{"Hours": 0},{"Hours": 0},{"Hours": 0}],Total:0}; 

表顯示self.List()這是映射到data.Lines的observableArray與self.List(ko.mapping.fromJS(data.Lines)())

[{"Entries":[{"Hours":"33.5"},{"Hours":2.5},{"Hours":3.75}],"Total":39.75},{"Entries":[{"Hours":5.1},{"Hours":2},{"Hours":4.75}],"Total":11.85},{"Entries":[{"Hours":1.2},{"Hours":3},{"Hours":2.12}],"Total":6.32}] 

當我點擊addRow按鈕,我想我需要重新計算self.List()。我從why-can-not-i-concat-data-to-observable-array-in-knockout

self.addRow =function(){ 
    self.List(self.List().concat(data1)) 
    self.applyTotals(); 
} 

applyTotoals工作正常,嘗試,如果我不添加行。

self.applyTotals = function(){ 
    ko.utils.arrayForEach(self.List(), function(vm){ 
     vm.Total = ko.computed(function(){ 
      var s = 0; 
      ko.utils.arrayForEach(this.Entries(), function(entry){ 
       var p = parseFloat(entry.Hours(), 10); 
       if (!isNaN(p)) { 
        s += p; 
       } 
      }); 
      return s; 
     }, vm); 
    }); 
}  

但我得到uncaught TypeError:this.Entries is not a function,新行不會計算總數。所以我試過

self.addRow =function(){ 
    self.List = ko.computed(function(){ 
     var orig = self.List(); 
     var os= ko.toJS(orig); 
     os.push(data1) 
     console.log(JSON.stringify(os)) 
     var oa = ko.observableArray([]); 
     return oa(ko.mapping.fromJS(os)());    
    }) 
} 

如何修改映射的observableArrray?

這裏是小提琴:http://jsfiddle.net/mckennatim/jngesuf2/

回答

2

以及@mcktimo你沒有有效利用mapping插件。你可以在fromJS函數中使用2nd paramter Mapper並有效地建立你的viewModel。

視圖模型:

function model(data) { 
    var self = this; 
    self.Entries = ko.observableArray(); 
    self.Total = ko.computed(function() { 
     var sum = 0; 
     ko.utils.arrayForEach(self.Entries(), function (entry) { 
      var value = parseFloat(entry.Hours(), 10); 
      if (!isNaN(value)) { 
       sum += value; 
      } 
     }); 
     return sum; 
    }); 
    ko.mapping.fromJS(data, {}, self); 
} 

var mapping = { //everything goes through this point 
    create: function (options) { 
     return new model(options.data); 
    } 
} 

function ViewModel() { 
    var self = this 
    self.List = ko.observableArray([]) 
    self.LoadData = function (data) { 
     ko.mapping.fromJS(data.Lines, mapping, self.List) 
    } 
    self.LoadData(data); 
    self.addRow = function() { 
     self.List.push(ko.mapping.fromJS(data1, mapping)); 
    } 
} 
ko.applyBindings(new ViewModel(), document.getElementById('ko')) 

工作樣本here

我建議採取更加深入地瞭解映射documentation

相關問題