Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous value of an observable in subscribe of same observable

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
});
like image 648
KodeKreachor Avatar asked Oct 10 '12 15:10

KodeKreachor


3 Answers

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) {

});
like image 68
JBeagle Avatar answered Oct 08 '22 11:10

JBeagle


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");
like image 90
RP Niemeyer Avatar answered Oct 08 '22 11:10

RP Niemeyer


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;
};
like image 21
Andries Avatar answered Oct 08 '22 11:10

Andries