Knockout-Contrib / Knockout-Contrib/Knockout-Validation
Custom binding Interceptor pattern not working
- Dominant language
- JavaScript
- Stars
- 1k
- Forks
- 366
- PR merge metrics
- No merged PRs in 30d
Description
Hi
I'm trying to enforce numeric values tomy viewmodel properties (also retain type) so i am using a custom binding with and interceptor that will convert strings to numbers.
Since I'm using a wrapper/interceptor the actual viewmodel property which already has validation rules, the error messages do not show (although the view model property is invalid).
Here is a workaround i found although it is pretty ugly. Any other solution ?
``` js
ko.bindingHandlers.numericValue = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
var interceptor = ko.computed({
read: underlyingObservable,
write: function (value) {
underlyingObservable(parseFloat(value));
}
});
//TODO: force the textbox to react to underlyingObservable validation changes
// Something like a deep copy
if (valueAccessor().rules != "undefined") {
interceptor.extend({ validatable: true });
interceptor.rules = valueAccessor().rules;
interceptor.__valid__ = valueAccessor().__valid__;
interceptor.isModified = valueAccessor().isModified;
interceptor.isValid = valueAccessor().isValid;
interceptor.isValidating = valueAccessor().isValidating;
}
ko.bindingHandlers.value.init(element, function () { return interceptor; }, allBindingsAccessor);
},
update: ko.bindingHandlers.value.update
};
```
Contributor guide
Research direction
Start with the custom ko.bindingHandlers.numericValue interceptor shown in the issue, then trace how it delegates to ko.bindingHandlers.value and the validatable extension. Reproduce the case where the underlying viewmodel property is invalid, and consider the work complete when numeric conversion is retained and its validation messages appear through the wrapper.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100