Created
February 10, 2015 14:27
-
-
Save cmaas/de3e83b56e686e3c81f2 to your computer and use it in GitHub Desktop.
Knockout: Force a positive integer
This file contains hidden or 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
// 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