How can I get two computed values to bind to each other?

后端 未结 1 993
渐次进展
渐次进展 2020-12-11 22:32

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:

相关标签:
1条回答
  • 2020-12-11 22:37

    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/

    0 讨论(0)
提交回复
热议问题