更改属性文本并使用挖空保留输入的值

Change attribute text and keep value of an input with knockout

本文关键字:保留 输入 属性 文本      更新时间:2023-09-26

对不起我的英语...不是很好,但我会尝试解释我的问题。我得到了一个包含一些输入字段的表单,该字段必须以货币格式显示值,但该字段的属性"value"必须为float类型。恢复:我希望输入以货币格式显示他的值,但不更改他的浮点值。我正在使用 Knockout 来绑定值。以上是我的一次尝试:网页代码:

    <input data-bind="value: unit_price, attr:{text: $parent.currency($data.unit_price())}" type="text" name="unit_price" class="align_right unit_price_col" />

淘汰赛:

    self.currency = ko.computed({
         read: function(key) {
    },
     write: function(value) {
         console.log(value); // Value of the input
     }
    });
我的尝试是尝试创建一个计算函数,当值更改时,该函数接收该值,将值格式化

为货币,并且仅更改属性文本以显示格式化值,而不更改可观察量的值。这可能吗?

谢谢

计算隐藏了真正的可观察对象,当前版本的 KO 的唯一解决方案是公开值,例如

http://jsfiddle.net/Pv3f8/

ko.extenders.currency = function(observable, options) {
    var wrapped = ko.computed({
        write: observable,
        read: function() {
            return Globalize.format(observable(), "c" );
        }
    });
    wrapped.raw = observable;
    return wrapped;
};

我已经向KO团队建议他们应该引入第三个功能format它由bindnigHandlers使用,这样您的可观察量始终返回实际值,但视图使用格式化的值。在此之前,这是一种方式

更新:如果要使用值绑定更新输入中的值,则需要更具创意,因为它将是一个字符串

http://jsfiddle.net/Pv3f8/1/