Search code examples
javascriptknockout.jsknockout-mapping-plugin

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


How do you add a row to an editable table in 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};

The table displays self.List() which is an observableArray mapped to data.Lines with 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}]

When I click the addRow button I am thinking I need to recompute self.List(). I have tried from why-can-not-i-concat-data-to-observable-array-in-knockout

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

applyTotoals works fine if I don't add a row.

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

but I get uncaught TypeError:this.Entries is not a function and the new row won't compute totals. So I have tried

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

How do I modify a mapped observableArrray?

Here is the fiddle: http://jsfiddle.net/mckennatim/jngesuf2/


Solution

  • well @mcktimo you are not effectively using mapping plugin . you can make use of 2nd paramter Mapper in fromJS function and build you viewModel effectively .

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

    working sample here

    I suggest to take a deeper dive into the mapping documentation