覆盖要计算的JSON属性 [英] overriding a JSON property to be computed

查看:79
本文介绍了覆盖要计算的JSON属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是敲门游戏.js的新手,如果这是一个简单的问题,请原谅.

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

我正在从Web服务获取JSON数据,该Web服务已经包含需要计算的属性.像

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
}

ValueSumofValues必须是ValueA和ValueB的总和.我想使用映射插件来创建我的视图模型,但是要覆盖SumOfValues的创建,以便对其进行计算.当Viewmodel转换回JSON数据(用于发布回Web服务)时,我希望SumOfValues包含正确的总和.

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.

jsfiddle 中,我的工作很好,唯一的问题是SumofValues属性没有当我更改其中一个文本框的值时,不会更新.我认为该值将自动取决于ValueA和ValueB,因为我在函数中引用了它们.

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.

谢谢

推荐答案

您需要更改SumOfValues的映射以创建计算值而不是可观察值.这是执行此操作的更新小提琴:

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/

和代码:

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

这篇关于覆盖要计算的JSON属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆