Is there a way to reject/cancel the modification of an observable's value? Like this:
observable.subscribe (function (newvalue) {
if ( newvalue < 0 ) {
// cancel changing
}
else{
// proceed with change
}
}, this)
Edit:
I found something else: Writeable computed observables.
Here is an example:
function AppViewModel() {
this.field = ko.observable("initValue");
this.computedField = ko.computed({
read: function () {
return this.field();
},
write: function (value) {
if(value > 0) {
this.field(value);
}
},
owner: this
});
}
So then you bind to the computed field.
/Edit
I would go with a custom binding.
Here is the tutorial for custom binding: http://learn.knockoutjs.com/#/?tutorial=custombindings
or here is the documentation: http://knockoutjs.com/documentation/custom-bindings.html
To help reject write values I used the following:
I extended Knockout with this code:
ko.conditionedObservable = function (initialValue, condition) {
var obi = ko.observable(initialValue);
var computer = ko.computed({
read: function () { return obi(); },
write: function (newValue) {
//unwrap value - just to be sure
var v = ko.unwrap(newValue);
//check condition
if (condition(v)) {
//set it to the observable
obi(v);
}
else {
//reset the value
computer.notifySubscribers();
}
}
});
return computer;
};
Use it in the object like this:
field = ko.conditionedObservable<number>(null, (v) => parseInt(v) > 0);
For more explanation check my Conditioning Knockout Observables: reject values blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With