Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

knockout.js - How can I get two computed values to bind to each other?

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();
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...