knockout Interdependent variables

家住魔仙堡 提交于 2019-12-13 07:01:37

问题


I have knockout variables that are Interdependent .

Exempla :

var _CostNoVAT =  ko.observable(0);
var _CostIncludeVAT =  ko.observable(0);
var _VAT= 0.50;

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)

How can I do it?

regards, yaniv abo


回答1:


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,output




回答2:


Use one as the canonical value then derive the other to\from it. Say we make _CostNoVAT the canonical form then when the user enters cost with VAT you set the costNovat variable to 6.66 then allow it to trickle to _ConstIncudeVAT.



来源:https://stackoverflow.com/questions/22693635/knockout-interdependent-variables

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