-
-
Save jonathancounihan/0b5f9290b71d53d1c5f974aecb1aac11 to your computer and use it in GitHub Desktop.
Knockout extender to force a field to be an integer value within a specified range.
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.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 ) { | |
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment