Skip to content

Instantly share code, notes, and snippets.

@jonathancounihan
Forked from hereswhatidid/range.knockout.js
Created May 12, 2019 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathancounihan/0b5f9290b71d53d1c5f974aecb1aac11 to your computer and use it in GitHub Desktop.
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.
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