剔除相关变量 [英] knockout Interdependent variables
问题描述
我有一些相互依存的剔除变量.
I have knockout variables that are Interdependent .
示例:
var _CostNoVAT = ko.observable(0);
var _CostIncludeVAT = ko.observable(0);
var _VAT= 0.50;
如果用户将_CostNoVAT更改为10,则_CostIncludeVAT必须为15(10 *(1 + VAT) 如果用户将_CostIncludeVAT更改为10,则_CostNoVAT必须为6.66(10/(1 + VAT)
if the user Change the _CostNoVAT to 10 then _CostIncludeVAT need to be 15 (10*(1+VAT) if the user Change the _CostIncludeVAT to 10 then _CostNoVAT need to be 6.66 (10/(1+VAT)
我该怎么办?
致谢, yaniv abo
regards, yaniv abo
推荐答案
您可以通过将其中一个可观察对象转换为可写计算对象来实现此目的.在这里,_CostIncludeVAT
是可写的计算值.更改后,将执行其write
函数,该函数实际上会更改_CostNoVAT
的值.然后将触发其read
函数执行...
You can do this by turning one of the observables into a writeable computed. Here, _CostIncludeVAT
is a writeable computed. When it's changed, its write
function is executed which actually changes the value of _CostNoVAT
; that will then trigger its read
function to execute...
function VM () {
this._VAT= 0.50;
this._CostNoVAT = ko.observable(0);
this._CostIncludeVAT = ko.computed({
read: function () {
return this._CostNoVAT() * (1 + this._VAT);
},
write: function(value) {
this._CostNoVAT(value / (1 + this._VAT));
},
owner: this
});
}
ko.applyBindings(new VM());
JsBin: http://jsbin.com/vizopico/1/edit? html,js,输出
这篇关于剔除相关变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!