我有一些扩展程序代码,我希望能够同时使用。一旦我尝试使用Range扩展Numeric,问题就不起作用了。
form
这是另一个扩展者......
ko.extenders.numeric = function (target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
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);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
这是我的小提琴https://jsfiddle.net/xequence/0nL09w55/
以下是违规实施
ko.extenders.range = function (target, intRange) {
//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) {
alert(target());
var current = target(),
newValueAsNum = isNaN(newValue) ? 0 : parseInt(+newValue, 10),
valueToWrite = newValueAsNum;
if (newValueAsNum < intRange.min) {
valueToWrite = intRange.min;
}
if (newValueAsNum > intRange.max) {
valueToWrite = intRange.max;
}
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the tested value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
答案 0 :(得分:2)
请参阅我认为可以显示您想要的行为的this fiddle。
我稍微简化了示例并进行了以下更改:
范围扩展器期待具有min
的对象
和max
属性。我改变了这一点,以便调用extend
传递对象而不仅仅是数值。
数字扩展程序正在使用ko.pureComputed
而不是ko.computed
。由于该功能有副作用,我认为你应该使用ko.computed
。有关详情,请参阅knockout.js docs page。
范围扩展器使用parseInt
,它会覆盖数字扩展器中完成的任何舍入。两者现在都使用parseFloat
。