Is it possible in knockout to get the current value of an observable within a subscription to that observable, before it receives the 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's set to newValue
});
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 like this:
MyViewModel.MyObservableProperty.subscribeChanged(function (newValue, oldValue) {
});
There is a way to do a subscription to the before value like this:
this.myObservable = ko.observable();
this.myObservable.subscribe(function(previousValue){
//I'd like to get the previous value of 'myObservable' here before it's set to newValue
}, this, "beforeChange");
Little change to Beagle90 answer. Always return the subscription itself to be able to access the dispose() for instance.
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;
};
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