Reject observed change in value

Is there a way to reject / discard a change in the observed value? Like this:

observable.subscribe (function (newvalue) { if ( newvalue < 0 ) { // cancel changing } else{ // proceed with change } }, this) 
+6
source share
2 answers

Edit:

I found something else: Recorded 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, you are attached to the calculated field.

/ Edit

I would go with custom binding.

Here is a tutorial for custom binding: http://learn.knockoutjs.com/#/?tutorial=custombindings

or here is the documentation: http://knockoutjs.com/documentation/custom-bindings.html

+8
source

To help reject the record values, I used the following:

  • Create a hidden observable that stores value.
  • Returns a recordable computed observable based on a hidden observable.
  • When something is written to the calculated observable, confirm it before accepting it.

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 an object as follows:

 field = ko.conditionedObservable<number>(null, (v) => parseInt(v) > 0); 

For more information, check out my Knockout Registration Notice: Reject Blog Values .

0
source

All Articles