如何让两个计算值相互绑定? [英] How can I get two computed values to bind to each other?

查看:19
本文介绍了如何让两个计算值相互绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是保持两个文本框的数学同步.我使用的字段是小计、taxTotal、税率和销售总额.我想要发生的是:

What I'm trying to do is keep two text box's math in sync. The fields I'm working with is subtotal, taxTotal, tax rate, and sale total. What I want to happen is:

  • 如果用户更新了 taxRate,则 taxTotal 将更新为正确的金额(subTotal * taxRate).
  • 如果用户更新了 taxTotal,则应使用正确的金额更新 taxRate(taxTotal/subTotal * 100)

我对此并没有深入了解,我认为这是因为我一直在考虑具有支持字段的属性(例如在 C# 中),并且我在试图找出保持一切绑定的逻辑时遇到了麻烦,并且在淘汰框架内可观察到(管理脏状态等).

I didn't get very far with this, and I think it's because I keep thinking in terms of properties with backing fields (like in C#) and I'm having trouble trying to figure out the logic to keep everything bound and observable within the knockout framework (managing dirty states etc).

有没有人有解决方案?据我所知,我使用 pureComputed 而不是计算.例如

Does anyone have a solution for this? As far as I got led me to using pureComputed instead of computed. e.g.

this.subTotal = ko.observable(0.00);

this.taxRate = ko.pureComputed({
     read: function(){

     },
     write: function(){

     },
     owner: this
});

this.taxTotal = ko.pureComputed({
    read: function(){

     },
     write: function(){

     },
     owner: this
});

this.saleTotal = ko.computed(function(){
    return this.subTotal ()+ this.taxTotal();
});

推荐答案

这是一个很有趣的问题.一个规则定义了 taxTotal 计算的读取函数,另一个定义了写入函数.另外两个变量只是可观察的.我省略了 100 乘数,因为它不对称.它需要在两个函数中都存在,或者两者都不存在.

This was a fun one to figure out. One rule defines the read function for the taxTotal computed, the other defines the write function. The other two variables are just observables. I left out the 100 multiplier because it wasn't symmetric. It needs to be in both functions or neither.

var viewModel = (function () {
    var subTotal = ko.observable(10),
        taxRate = ko.observable(5);


    var taxTotal = ko.computed({
        read: function () {
            return subTotal() * taxRate();
        },
        write: function (newValue) {
            taxRate(newValue / subTotal());
        }
    });

    return {
        taxRate: taxRate,
        taxTotal: taxTotal,
        subTotal: subTotal
    };
}());

ko.applyBindings(viewModel);

http://jsfiddle.net/ypsdh53q/

这篇关于如何让两个计算值相互绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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