javascript – Knockout.js在ko.observable()写之前修改值

前端之家收集整理的这篇文章主要介绍了javascript – Knockout.js在ko.observable()写之前修改值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个有很多变量的工作视图模型.

我在文本框中使用autoNumeric(http://www.decorplanit.com/plugin/)进行文本格式化.我想在计算的observable中使用输入字段的观察数据,但是如果具有格式的可观​​察文本字段被修改,格式化也会保存在变量中.

如何在没有格式化的情况下仅观察输入字段的值?

我认为最好的方法可能是observable的getter / setter,并在设置值时删除格式.我无法在knockout文档中找到为ko.observable()编写get / set方法解决方案,而ko.computed()无法存储值.

我不想使用隐藏字段或额外变量.
没有它可能吗?

最佳答案
解决方案,如http://knockoutjs.com/documentation/extenders.html所示

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;
};

后来

function Appviewmodel(one,two) {
  this.myNumberOne = ko.observable(one).extend({ numeric: 0 });
  this.myNumberTwo = ko.observable(two).extend({ numeric: 2 });
}

猜你在找的jQuery相关文章