如何获得两个相互绑定的计算值? [英] How can I get two computed values to bind to each other?
问题描述
我想做的是使两个文本框的数学保持同步.我正在使用的字段是小计,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,则应使用正确的金额(taxTotal/subTotal * 100)来更新taxRate
我对此并不太了解,这是因为我一直在考虑具有后备字段的属性(例如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代替了compute.例如
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);
这篇关于如何获得两个相互绑定的计算值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!