Overriding JSON Property for Computation
I'm a brand spanking newbie to knockout.js so sorry if this is a simple question.
I am receiving JSON data from a web service that already contains a property that needs to be calculated. Something like
{
ValueA: 1,
ValueB: 3,
SumOfValues: 0
}
SumofValues must be the sum of ValueA and ValueB. I want to use the mapping plugin to create my viewmodel, but override the creation of SumOfValues so that it is computed. When the ViewModel is converted back to JSON data (to send back to the web service), I want the SumOfValues to contain the correct amount.
It works well for me in jsfiddle , the only problem is that the SumofValues property is not updated when I change the value in one of the textboxes. I thought that this value would automatically depend on ValueA and ValueB because I am referencing them in the function.
thank
source to share
You need to change the display of SumOfValues to create a computed value, not an observed value. Here's an updated fiddle that does it:
and the code:
var json = {
"ValueA": 9,
"ValueB": 1,
"SumOfValues": 0
};
function myViewModel(data) {
var self = this;
var mapping = {
'SumOfValues': {
create: function (options) {
return ko.computed( function() {
return (parseInt( self.ValueA() ) + parseInt( self.ValueB() ) );
});
}
}
};
ko.mapping.fromJS(data, mapping, self);
self.isValid = ko.computed(function () {
return (self.SumOfValues() == self.ValueA() + self.ValueB() ? "equal" : "not equal");
});
}
ko.applyBindings(new myViewModel(json));
source to share
Calculated observables are read out of the box only. If you want the computed observable to be updated, you need to modify it to support read / write support. See the entry section in the knockout documentation for details . They are directly implemented. If you need a trial violin, let me know, but it will help you accomplish what you want.
source to share