Knockoutjs + ko.mapping.fromJS + computed field not calculate computed

1k views Asked by At

I try to do this:

myData = {weight: 100, anotherWeight: 120.55}; // when my data is plain json - all work

$.when($.getJSON(url, {param}, function(data) {myData = data} ).   
 //when i got it from ajax - dosn't work
then(function(){
  var taskModel = function(data)
  {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
    this.computedWeight = ko.computed(function () { return self.weight() + 
       ' ---- ' + 
       self.anotherWeight() + ' kg'; });
  }
  ko.applyBindings(new taskModel(myData));
});

<input type="text" data-bind="value: weight"/><br/>
<input type="text" data-bind="value: anotherWeight"/><br/>
<span data-bind="text: computedWeight"></span>

First time - after loading - computedWeight is calculate right. But when I change weight or anotherWeight fields - computedWeight don't change.
Thanks.

1

There are 1 answers

1
Alexander Taran On BEST ANSWER

Try ko.mapping.fromJSON() instead of ko.mapping.fromJS()