In the following code the idea is that if you fill in ‘test’ that this is considered invalid and shouldn’t write the value to the observable. The problem I have is that my custom binding is somehow resetting the observable’s value.
A working version of the code below: http://jsfiddle.net/6hcpM/1/
var underlying = ko.observable('foo');
var errors = ko.observableArray()
var isValid = ko.dependentObservable(function(){
return errors().length === 0
});
var vm = {
name : ko.dependentObservable({
read : underlying,
write : function(value){
errors([]);
if(value==='test'){
errors([ 'Cant be test matey' ]);
};
if(isValid()){
underlying(value);
};
}
})
};
vm.name.isValid = isValid;
ko.bindingHandlers.validateCss = {
update: function(element, valueAccessor) {
observable = valueAccessor();
observable.isValid(); //this somehow causes the problem
}
};
ko.applyBindings(vm);
Your
validateCssbinding creates a dependency tovm.name.isValid. When you write “test” to the field,errorsis updated, which causesisValidto update, which triggers all of the bindings in the input’sdata-bindattribute to be re-evaluated. So, thevaluebinding gets evaluated again and replaces the current value with the value fromname(which is stored inunderlying).So, basically the
valuebinding is running again based onisValidchanging.There are several ways that you could handle it. You could let
underlyingget updated every time and, if necessary, store a clean value elsewhere that only gets updated when it is valid.You could also put your custom binding on a different element. For example, you could wrap your
inputin a span or div and put the binding on it. I assume that you want thevalidateCssbinding to assign a CSS class when the value is invalid.