overriding a JSON property to be computed

 ̄綄美尐妖づ 提交于 2019-12-12 00:27:50

问题


I am brand spanking new to knockout.js so forgive if this is a trivially easy question.

I am getting JSON data from a web service that already contains a property that needs to be computed. Something like

{
    ValueA: 1,
    ValueB: 3,
    SumOfValues: 0
}

SumofValues needs to 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 into JSON data (for posting back to the web service), I want SumOfValues to contain the correct sum.

I have this working pretty well in this jsfiddle, the only problem is that the SumofValues property doesn't update when I change the value in one of the textboxes. I thought this value would automatically be dependent on ValueA and ValueB because I reference them in the function.

thanks


回答1:


You need to change your mapping of SumOfValues to create a computed value rather than an observable value. Here is an updated fiddle that does this:

http://jsfiddle.net/38MwU/11/

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



回答2:


Computed observables are read only out of the box. If you want the computed observable to be updated you need to modify it to support read/write. Look at the writeable section in the knockout documentation for details. They are straight forward to implement. If you need a sample fiddle let me know but this should help you accomplish what you want



来源:https://stackoverflow.com/questions/20534172/overriding-a-json-property-to-be-computed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!