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

时间:2021-09-23 20:37:33

I've got a working viewmodel with numerous variables.

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

I use autoNumeric (http://www.decorplanit.com/plugin/) for text formatting in textbox. I'd like to use the input field's observed data in a computed observable, but if the observable textfield with the formatting gets modified, the formatting also gets saved in the variable.

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

How can I only observe the value of the input field without the formatting?

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

I think the best way to this could be a getter/setter to the observable, and remove the formatting when the value is set. I couldn't find a solution in knockout's documentation to write get/set methods for ko.observable(), and ko.computed() can not store a value.

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

I don't want to use hidden fields, or extra variables.
Is this possible without it?

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

2 个解决方案

#1


3  

Solution, as seen on http://knockoutjs.com/documentation/extenders.html

解决方案,如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;
};

And later on

后来

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

#2


1  

You can use ko.computed() for this. You can specify a write option, see Writeable computed observables

你可以使用ko.computed()。您可以指定写入选项,请参阅可写计算的可观察量

Example (taken from knockout documentation):

示例(取自淘汰文档):

function MyViewModel() {
   this.price = ko.observable(25.99);

   this.formattedPrice = ko.computed({
       read: function () {
           return '$' + this.price().toFixed(2);
       },
       write: function (value) {
           // Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
           value = parseFloat(value.replace(/[^\.\d]/g, ""));
           this.price(isNaN(value) ? 0 : value); // Write to underlying storage
       },
       owner: this
   });
}

ko.applyBindings(new MyViewModel());

#1


3  

Solution, as seen on http://knockoutjs.com/documentation/extenders.html

解决方案,如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;
};

And later on

后来

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

#2


1  

You can use ko.computed() for this. You can specify a write option, see Writeable computed observables

你可以使用ko.computed()。您可以指定写入选项,请参阅可写计算的可观察量

Example (taken from knockout documentation):

示例(取自淘汰文档):

function MyViewModel() {
   this.price = ko.observable(25.99);

   this.formattedPrice = ko.computed({
       read: function () {
           return '$' + this.price().toFixed(2);
       },
       write: function (value) {
           // Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
           value = parseFloat(value.replace(/[^\.\d]/g, ""));
           this.price(isNaN(value) ? 0 : value); // Write to underlying storage
       },
       owner: this
   });
}

ko.applyBindings(new MyViewModel());