How can I get two computed values to bind to each

2019-01-20 13:46发布

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:

  • If the taxRate is updated by the user, then the taxTotal will update with the correct amount (subTotal * taxRate).
  • If the taxTotal is updated by the user, then the taxRate should be updated with the correct amount (taxTotal / subTotal * 100)

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).

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();
});

标签: knockout.js
1条回答
再贱就再见
2楼-- · 2019-01-20 14:12

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/

查看更多
登录 后发表回答