带有淘汰的货币格式 [英] Currency Format with Knockout
问题描述
我知道之前已经有人回答了,这是它的代码(Knockout JS)
I know that it's been answered before and here's the code for it (Knockout JS)
ko.observable.fn.withCurrencyFormat = function (precision) {
var observable = this;
observable.formatted = ko.computed({
read: function (key) {
return '$' + (+observable()).toFixed(precision);
},
write: function (value) {
value = parseFloat(value.replace(/[^\.\d]/g, ""));
observable(isNaN(value) ? null : value); // Write to underlying storage
}
});
return observable;
};
但是我该如何处理这些情况?
But how can I handle these scenarios?
- 用户删除文本字段中的0.00,默认返回 到0.00,而不是保持空白
- 用户在文本中输入字母 字段,它还应该默认返回0.00,而不是返回NaN
- User deletes the 0.00 in the text field, it should default back to 0.00 instead of staying blank
- User types letters in the text field, it should also default back to 0.00 instead of returning NaN
推荐答案
在生成输出的read
函数中,在此处创建NaN
:
In your read
function, which generates the output, the NaN
is created here:
+observable() // The + tries to "cast" the observable's value to a number
要摆脱NaN
,您必须做一次isNaN
检查:
To get rid of the NaN
, you'll have to do an isNaN
check:
var nr = +observable();
if (isNaN(nr)) {
nr = 0;
}
现在,在转换输入的write
方法中,将为无效输入返回一个null
值.将其替换为0
以默认为$0.00
:
Now, in your write
method, which transforms the input, there's a null
value returned for invalid input. Replace this to 0
to default to $0.00
:
observable(isNaN(value) ? 0 : value);
如果可以确定计算出的formatted
是对基础可观察值的唯一写操作,则只需修复其中之一(即,在将值输入到系统或输出时决定格式化值).
If you can be sure the formatted
computed is the only one writing to the underlying observable, you only need to fix one of these (i.e. you decide to format values on inputting them to the system or on outputting them).
下面的代码片段显示了链接到输入的这些修复程序.我个人认为,此行为更适合扩展器,但我不确定是否这很重要.
The snippet below shows these fixes linked to an input. Personally, I think this behavior is better suited for an extender, but I'm not sure if it matters.
ko.observable.fn.withCurrencyFormat = function (precision) {
var observable = this;
observable.formatted = ko.computed({
read: function (key) {
var nr = +observable();
if (isNaN(nr)) nr = 0;
return '$' + nr.toFixed(precision);
},
write: function (value) {
value = parseFloat(value.replace(/[^\.\d]/g, ""));
observable(isNaN(value) ? 0 : value);
}
}).extend({notify: 'always'});
return observable;
};
var obs = ko.observable(0).extend({notify: 'always'});
var val = obs.withCurrencyFormat(2).formatted;
ko.applyBindings({
val: val
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: val">
这篇关于带有淘汰的货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!