Alan February 2016

ComputedObservables doesn't recalc after ko.mapping.fromJS

I'm using KnockoutJS and I have a nested ViewModel-Structure with Computed Observables on each level. The parent levels contains totalization of it's children. The datastructure looks like this (simplyfied):

vm.clientsRawData = [
    {
        ClientName: "Thomas",
        MoneyAccounts: [
            {
                Currency: "USD",
                Amount: "1000"
            }
            {
                Currency: "EUR",
                Amount: "2000"
            }
        ]
    },
    {
        ClientName: "Ann",
        MoneyAccounts: [
            {
                Currency: "CHF",
                Amount: "4000"
            }
            {
                Currency: "EUR",
                Amount: "1500"
            }
        ]
    }
]

After initializing the ViewModel (using ko.mapping.fromJS) I saw that the ComputedObservables on the "Top-Level (for instance, vm.AllUsd(), containing the Sum of each clients Usd MoneyAccounts)" didn't refresh. The Sum is still 0. What do i have to do to Calculate this total amounts within the Mapping of the JS-Structure?

I've already tried to achieve this with dummy-observables, but this extremely slows down the Loading-Process (Browser overwhelmed, hanging up)

Thanks in advance

UPDATED: For instance, this example. I found out, that the Client-Count is 0 after inizialization. But why?

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

Answers


Alan February 2016

Ok, got it. I had to call the clients observableArray like this:

vm.clients(ko.mapping.fromJS(data, ClientsMapping)())

Many thanks Eric for pointing me to the right direction. You saved me! :-)

Post Status

Asked in February 2016
Viewed 3,274 times
Voted 8
Answered 1 times

Search




Leave an answer