Last active
August 29, 2015 14:16
-
-
Save raducugheorghe/403a99891df389924514 to your computer and use it in GitHub Desktop.
[Javascript][Knockout] Numeric extender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ko.extenders.numeric = function (target, params) { | |
var options = { | |
precision: 0, | |
allowNegative: false | |
}; | |
$.extend(options, params); | |
//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, options.precision), | |
newValueAsNum = (isNaN(newValue) || | |
(options.allowNegative && newValue < Number.MIN_SAFE_INTEGER) || | |
(!options.allowNegative && (newValue < 0)) || | |
newValue > Number.MAX_SAFE_INTEGER) | |
? current : 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment