在绑定到输入字段时,这似乎是一种使用淘汰赛清理/验证/格式化数据的常用方法,它创建了一个可重用的自定义绑定,该绑定使用计算的 observable。它基本上扩展了默认值绑定以包含一个拦截器,该拦截器将在写入/读取之前格式化/清理/验证输入。
ko.bindingHandlers.amountValue = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
var interceptor = ko.computed({
read: function () {
// this function does get called, but it's return value is not used as the value of the textbox.
// the raw value from the underlyingObservable is still used, no dollar sign added. It seems like
// this read function is completely useless, and isn't used at all
return "$" + underlyingObservable();
},
write: function (newValue) {
var current = underlyingObservable(),
valueToWrite = Math.round(parseFloat(newValue.replace("$", "")) * 100) / 100;
if (valueToWrite !== current) {
// for some reason, if a user enters 20.00000 for example, the value written to the observable
// is 20, but the original value they entered (20.00000) is still shown in the text box.
underlyingObservable(valueToWrite);
} else {
if (newValue !== current.toString())
underlyingObservable.valueHasMutated();
}
}
});
ko.bindingHandlers.value.init(element, function () { return interceptor }, allBindingsAccessor);
},
update: ko.bindingHandlers.value.update
};
jsFiddle 示例:http: //jsfiddle.net/6wxb5/1/
我错过了什么吗?我已经看到到处都在使用这种方法,但它似乎并没有完全奏效。读取功能似乎完全没用,因为它根本没有被使用..,在写入功能中,输入“23.0000”会将写入的值更改为 23,但文本框的值不会更新。