Let's say that I wish to have the behaviour a ko.computed has with:
- read
- write
but I want to have an internal observable inside that ko.computed property, something like:
this.a = ko.computed(function() {
value: ko.observable(null),
read: function() {
return value;
},
write: function(newValue) {
if (newValue) {
value(newValue);
}
}
});
Is this possible in some manner? The above doesn't work.
It looks like what you want is an observable that doesn't allow assignments that fail validation. You can do that with an extender on an ordinary observable:
Call it like so to prevent assignment of falsy values:
Update: It's possibly significant that the above method does allow the assignment before correcting it. If it is important that the observable never take an invalid value, a computed (structured much like Anders' solution) can be used.
Demo http://jsfiddle.net/o641v37L/1/ (uncomment the assignment to use the computed)