Get the previous observed value in the subscription of the same observed

Is it possible to knock out the current value of the observable within the subscription to the observable before it receives a new value?

Example:

this.myObservable = ko.observable(); this.myObservable.subscribe(function(newValue){ //I'd like to get the previous value of 'myObservable' here before it set to newValue }); 
+69
Oct 10 '12 at 15:25
source share
5 answers

There is a way to subscribe to a value before the following:

 this.myObservable = ko.observable(); this.myObservable.subscribe(function(previousValue){ //I'd like to get the previous value of 'myObservable' here before it set to newValue }, this, "beforeChange"); 
+76
Oct. 10 '12 at 16:24
source share
 ko.subscribable.fn.subscribeChanged = function (callback) { var oldValue; this.subscribe(function (_oldValue) { oldValue = _oldValue; }, this, 'beforeChange'); this.subscribe(function (newValue) { callback(newValue, oldValue); }); }; 

Use the above:

 MyViewModel.MyObservableProperty.subscribeChanged(function (newValue, oldValue) { }); 
+125
Aug 12 '13 at 9:49
source share

A slight change in Beagle90's answer. Always return a subscription to be able to access the utility (), for example.

 ko.subscribable.fn.subscribeChanged = function (callback) { var oldValue; this.subscribe(function (_oldValue) { oldValue = _oldValue; }, this, 'beforeChange'); var subscription = this.subscribe(function (newValue) { callback(newValue, oldValue); }); // always return subscription return subscription; }; 
+15
Dec 22 '14 at 9:35
source share

pulling a request to add this function has a different code that ends better than relying on the beforeChange event.

All credits for Michael Best solution

 ko.subscribable.fn.subscribeChanged = function (callback) { var savedValue = this.peek(); return this.subscribe(function (latestValue) { var oldValue = savedValue; savedValue = latestValue; callback(latestValue, oldValue); }); }; 

To quote Michael:

I originally proposed using beforeChange to solve this problem, but since then I realized that it is not always reliable (for example, if you call valueHasMutated() on the observable).

+12
Mar 05 '15 at 23:55
source share

I found that I can call peek () from a writeable record to get the before value.

Something like this (see http://jsfiddle.net/4MUWp ):

 var enclosedObservable = ko.observable(); this.myObservable = ko.computed({ read: enclosedObservable, write: function (newValue) { var oldValue = enclosedObservable.peek(); alert(oldValue); enclosedObservable(newValue); } }); 
+3
Apr 08 '13 at 15:36
source share



All Articles