2

This is my first post here after trying to google an answer. If this had been answered somewhere before then if you could help directing me to right place that would be great.

I am trying to figure out a way to do 2 way binding between 2 fields.

I have a 2 fields on my form that do weight calculation. If you enter weight in pounds into field #1 then Knockout will calculate the weight in kilograms into field #2. I have no problem with this one and here is my jsfiddle for this http://jsfiddle.net/ubiquitous_tom/tVh3g/

var weight = 180;
self.weight = ko.observable(weight.toFixed(2));
self.weightKG = ko.computed(function(){
    var kg_weight = parseFloat(self.weight())/2.2;
    return !isNaN(kg_weight) ? kg_weight.toFixed(2) : undefined;
});

Now the problem I have is that when I'm trying to put weight in kilograms into field #2. It should calculate the weight in pounds into field #1 but it doesn't do it. I have no idea how to make it work because all the code that i try using computed "read" and "write" on both fields give me infinite loop error so I think I'm just not doing something right.

If anyone can help me out that would be great. I'm sure this is something super simple but I am totally new to Knockout and I am not quite sure how to make it work right. here's the jsfiddle for the one i'm trying to work on http://jsfiddle.net/ubiquitous_tom/VmZLZ/

var weight = 180;
self.weight = ko.observable(weight.toFixed(2));
self.weightKG = ko.computed({
    read: function() {
        return parseFloat(self.weight().toFixed(2));
    },
    write: function(newValue) {
        var kg_weight = parseFloat(newValue)/2.2;
        return !isNaN(kg_weight) ? kg_weight.toFixed(2) : undefined;
    }
});
4

1 回答 1

2

这是一个工作小提琴:http: //jsfiddle.net/jearles/VmZLZ/6/

关键是让可写计算的读取和写入都引用另一个可观察字段。当您读取计算时,它从“主”字段计算,当您写入计算时,它重新计算“主”字段。

--

function weightModel() {
    var self = this;
    var weight = 180;
    self.weight = ko.observable(weight.toFixed(2));
    self.weightKG = ko.computed({
        read: function() {
            return !isNaN(self.weight()) ? 
               (self.weight() / 2.2).toFixed(2) : undefined;
        },
        write: function(newValue) {
            var pd_weight = !isNaN(newValue) ?
                   (parseFloat(newValue) * 2.2).toFixed(2) : undefined;
            self.weight(pd_weight);
        }
    });
}
ko.applyBindings(new weightModel());
于 2013-04-24T01:42:45.883 回答