Knockout.js text相互依赖的输入字段

Knockout.js textInput fields dependent on each other

本文关键字:输入 字段 依赖 js text Knockout      更新时间:2023-09-26

所以用户想买一些土豆。他可以输入以公斤为单位的土豆数量,得到以美元为单位的总价,也可以反过来输入美元,得到公斤土豆。因此有2个输入字段。

要求:值必须在键入后立即更新。在一个字段中输入值会更新另一个字段,反之亦然。公斤必须保持完整,只有一个例外——当用户自己输入的不是完整重量时。

价格以美分为单位存储在内部。价格以每1000公斤美元的价格显示给用户。以千克为单位的数量总是整数。

这是我的代码:

var ViewModel = function () {
    var self = this;
    this.totalPrice = ko.observable();
    this.pricePerKg = ko.observable(999);
    this.potatoWeight = ko.computed({
        read: function () {
            var totalPrice = self.totalPrice();
            var potatoWeight = (totalPrice * 100) / self.pricePerKg() * 1000;
            return Math.round(potatoWeight);
        },
        write: function (potatoWeight) {
            var totalPrice = (potatoWeight * self.pricePerKg()) / 100 / 1000;
            self.totalPrice(totalPrice.toFixed(2));
        }
    });
};
ko.applyBindings(new ViewModel());

HTML:

<label for="potato">Potato, kg</label>
<input type="text" id="potato" data-bind="textInput: potatoWeight">
<label for="priceTotal">Price total, $</label>
<input type="text" id="priceTotal" data-bind="textInput: totalPrice">
<div> Price per 1000 kilogram:
<span data-bind="text: (pricePerKg() / 100).toFixed(2)">
</span>$

Js文件:https://jsfiddle.net/9td7seyv/13/

问题:当您在"土豆重量"中键入值时,它不仅会更新美元值,还会更新它本身。由于四舍五入会导致不一致。转到上面的jsfiddle,尝试在权重字段中键入500。当你进入最后一个零点时,它会变为501。

那么,有没有一种方法可以阻止字段更新本身,或者可能需要其他方法来解决这个问题?

对于这种情况,我能想到的最直接的方法是保存用户在任何计算后输入的值的副本。。。就像下面的代码一样。

var ViewModel = function () {
    var self = this;
    this.totalPrice = ko.observable();
    this.pricePerKg = ko.observable(999);
    this.weight=ko.observable();
    this.potatoWeight = ko.computed({
        read: function () {
            return self.weight();
        },
        write: function (potatoWeight) {
            var totalPrice = (potatoWeight * self.pricePerKg()) / 100 / 1000;
            self.totalPrice(totalPrice.toFixed(2));
                        self.weight(potatoWeight);
        }
    });
};
ko.applyBindings(new ViewModel());

https://jsfiddle.net/9td7seyv/16/

更新:对于两个值https://jsfiddle.net/9td7seyv/19/