Skip to content

Instantly share code, notes, and snippets.

@vmandic
Created November 28, 2016 13:01
Show Gist options
  • Save vmandic/c9309e306e3b6a13921b0ee113a705d4 to your computer and use it in GitHub Desktop.
Save vmandic/c9309e306e3b6a13921b0ee113a705d4 to your computer and use it in GitHub Desktop.
A knockout.js extension for a numberic observable. Limits the numeric observable to the provided min and max range args.
// requires knockout.js and jquery.js
// limits the numeric observable to the provided min and max range args
ko.extenders["limitedNumeric"] = (target: Ko.Observable<any>, args: any) => {
let settings: any = {
minValue: 1,
maxValue: null
};
$.extend(settings, args);
// create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, // always return the original observables value
write: (newValue: number) => {
if (settings.minValue && newValue < settings.minValue)
newValue = settings.minValue;
if (settings.maxValue && newValue > settings.maxValue)
newValue = settings.maxValue;
target(newValue);
}
});
// initialize with current value to make sure it is limited appropriately, and return the computed obs
result(target());
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment