Skip to content

Instantly share code, notes, and snippets.

@cmaas
Created February 10, 2015 14:27
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 cmaas/de3e83b56e686e3c81f2 to your computer and use it in GitHub Desktop.
Save cmaas/de3e83b56e686e3c81f2 to your computer and use it in GitHub Desktop.
Knockout: Force a positive integer
// extension to replace an observable with a writeable computed that forces write to be numeric
// original: https://github.com/tekpub/knockout-cart/blob/master/src/extensions.js
ko.observable.fn.asPositiveInteger = function(defaultForBadValue) {
var original = this,
interceptor = ko.computed({
read: original,
write: function(newValue) {
var parsed = parseInt(newValue, 10);
//if value is bad or negative, then use default
if (isNaN(parsed) || parsed < 0) {
parsed = defaultForBadValue
}
original(parsed);
}
});
//process the initial value
interceptor(original());
//return this new writeable computed to "stand in front of" our original observable
return interceptor;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment