如何附加到 Knockout.js 中的映射可观察数组?

How do I append to a mapped observable array in Knockout.js?

如何向 Knockout.js 中的 editable table 添加一行?

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

table 显示 self.List(),这是一个映射到 data.Linesself.List(ko.mapping.fromJS(data.Lines)())

的 observableArray
[{"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?

这里是 fiddle: http://jsfiddle.net/mckennatim/jngesuf2/

好吧@mcktimo 你没有有效地使用 mapping 插件。您可以在 fromJS 函数中使用 2nd paramter Mapper 并有效地构建您的 viewModel 。

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