0
我有一些擴展代碼,我希望能夠同時使用。一旦我嘗試用範圍擴展數字,問題就不起作用。淘汰賽擴展器不能同時工作
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;
};
這裏是另一個擴展...
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;
};
這裏是我的小提琴https://jsfiddle.net/xequence/0nL09w55/
這裏是違規實施
var InitializePanelsApplicantViewModel = function() {
this.CoverageLimit = ko.observable('').extend({required: true}).extend({numeric: 2}),
this.CoverageLimitFailWhyCry = ko.observable('').extend({required: true}).extend({numeric: 2}).extend({range : 500});
};
$(function(){
var masterVM = (function() {
this.InitializePanelsApplicantViewModel = new InitializePanelsApplicantViewModel();
})();
ko.applyBindings(masterVM);
});
感謝您澄清我使用parseInt而不是parseFloat。至於pureComputed,目前我對於我來說太新了,應該使用你對ko.computed的建議。 – Programmer