KnockoutJS货币绑定与实时更新

时间:2013-01-23 16:06:33

标签: javascript knockout.js

在我最近建造的Knockout界面中,我试图设置自动保存。它的设计使您在停止更改后1秒钟进行保存。

这是问题所在。默认情况下,KO依赖输入上的blur事件来更新viewModel。如果您在单击开箱之前离开页面或刷新浏览器,我的界面将不会保存数据。

为了解决这个问题,我启用了valueUpdate: 'afterkeydown',它适用于所有字符串输入。但是,我有一个数字PricePerLF字段,它被扩展,以便它始终包含一个数值。我使用了建议的扩展程序here

ko.extenders.numeric = function(target, precision) {
    //create a writeable computed observable to intercept writes to our observable
    var result = ko.computed({
        read: target,  //always return the original observables value
        write: function(newValue) {
            var current = target(),
                roundingMultiplier = Math.pow(10, precision),
                newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
                valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;

            //only write if it changed
            if (valueToWrite !== current) {
                target(valueToWrite);
            } else {
                //if the rounded value is the same, but a different value was written, force a notification for the current field
                if (newValue !== current) {
                    target.notifySubscribers(valueToWrite);
                }
            }
        }
    });

    //initialize with current value to make sure it is rounded appropriately
    result(target());

    //return the new computed observable
    return result;
};

如何使这个数字扩展器与valueUpdate: 'afterkeydown'一起玩得很好?强迫它显示一定数量的小数点也很好,例如2.80而不是2.8

1 个答案:

答案 0 :(得分:0)

我做了这个扩展器一段时间后,用afterkeydown尝试它并且它工作正常,如果你使用十进制格式它不太完美

http://jsfiddle.net/yEgmT/1/

ko.extenders.numeric = function(observable, format) {
    return ko.computed({
        read: function() {  
            return Globalize.format(observable(), format === true ? undefined : format);
        },
        write: function(value) {           
            if(value.substring) {
                value = Globalize.parseFloat(value)
            }                    
            if(!isNaN(value)) {
                observable(value);
            }
        }
    });
};