Frage

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;
    }
});
War es hilfreich?

Lösung

Here is a working fiddle: http://jsfiddle.net/jearles/VmZLZ/6/

The key is to have both the read and write of the writable computed reference the other observable field. When you read the computed it calculates from the "master" field, and when you write to the computed it re-calculates the "master" field.

--

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());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top