knockout Interdependent variables

2019-08-30 05:01发布

问题:

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.



标签: knockout.js