Search code examples
javascriptjqueryknockout.jsknockout-mapping-plugin

Adding new Observable to ObservableArray mapped by ko.mapping.fromJS


I'm trying to add a new Observable to an ObservableArray which has been mapped initially with KO's mapping plugin. But I don't get that working. Firebug is telling me "TypeError: totalChf is not a function". Looking at the added Observable, I notice that the Computed functions were not created. I've tried several methods, still without success... What am I missing?

Thanks in advance

Here the code:

var vm;
var ClientsMapping = {
  create: function (options) {
    var client = ko.mapping.fromJS(options.data, ContainersMapping)
    //Some computed observables for level one here...
    return client;
  }
}
var ContainersMapping = {
  'Containers': {
    create: function (options) {
      var container = ko.mapping.fromJS(options.data, MoneyAccountsMapping)
      container.totalChf = ko.computed(function () {
        var total = 0;
        $.each(container.MoneyAccounts(), function () {
          if (this.Currency() == "CHF") {
            total += this.Amount();
          }
        })
        return total;
      })
      //Some computed observables for level two here...
      return container;
    }
  }
}

var MoneyAccountsMapping = {
  'MoneyAccounts': {
    create: function (options) {
      var macc = new MoneyAccountModel(options.data)
      //Some computed observables for level three here...
      return macc;
    }
  }
}
var ClientModel = function (data) {
  ko.mapping.fromJS(data, {}, this);
}
var ContainerModel = function (data) {
  ko.mapping.fromJS(data, {}, this);
}
var MoneyAccountModel = function (data) {
  ko.mapping.fromJS(data, {}, this);
}
var data = [
  {
    'Clients': 'Thomas',
    'Containers': [
      {
        'ContName': 'Cont01',
        'MoneyAccounts': [
          { Currency: "CHF", Amount: 1000 },
        ]
      }
    ]
  },
{
  'Clients': 'Ann',
  'Containers': [
    {
      'ContName': 'Cont01',
      'MoneyAccounts': [
        { Currency: 'CHF', Amount: 1000 },
        { Currency: 'EUR', Amount: 500 }
      ]
    }
  ]
}
]

function viewModel() {
  var self = this;
  self.clients = ko.observableArray()
  self.clientsCount = ko.computed(function () {
    return self.clients().length
  })
}
$(function () {
  vm = new viewModel();
  vm.clients(ko.mapping.fromJS(data, ClientsMapping)());

  var cont1 = {
    'ContName': 'ContXX',
    'MoneyAccounts': [
      { Currency: "XXX", Amount: 1000 },
    ]
  };
  var cont2 = {
    'ContName': 'ContYY',
    'MoneyAccounts': [
      { Currency: "YYY", Amount: 1000 },
    ]
  };
  var cont3 = {
    'ContName': 'ContZZ',
    'MoneyAccounts': [
      { Currency: "ZZZ", Amount: 1000 },
    ]
  };
  var cont4 = {
    'ContName': 'ContWW',
    'MoneyAccounts': [
      { Currency: "WWW", Amount: 1000 },
    ]
  };

  vm.clients()[0].Containers.push(ko.mapping.fromJS(cont1, ContainersMapping));//Attempt1
  vm.clients()[0].Containers.push(ko.mapping.fromJS(cont2));//Attempt2
  vm.clients()[0].Containers.push(new ContainerModel(cont3));//Attempt3
  vm.clients()[0].Containers.push(ko.mapping.fromJS([cont4], ContainersMapping)()[0]);//Attempt4
  //...still no success.
})

Solution

  • You will generally want to keep your mappings independent of one another. A good way to do that is to define and perform the mappings within each class:

    var ClientModel = function(data) {
      var mapping = {
        'Containers': {
          create: function(options) {
            var container = new ContainerModel(options.data)
    
            //Some computed observables for level two here...
            return container;
          }
        }
      }
      ko.mapping.fromJS(data, mapping, this);
    }
    

    Once this is organized, you have a couple options for adding a new item to the observableArray:

    1. Create the new item and push it to the array:

      vm.clients()[0].Containers.push(new ContainerModel(cont1))
      
    2. Specify a key option in your mapping:

      var mapping = {
          'Containers': {
            key: function(item) {
              return ko.unwrap(item.ContName);
            },
            create: function(options) {
              var container = new ContainerModel(options.data)
      
              //Some computed observables for level two here...
              return container;
            }
          }
      }
      

      Then use mappedCreate to add the item:

      vm.clients()[0].Containers.mappedCreate(cont1);
      

    JSFiddle