Get previous value of an observable in subscribe of same observable

KodeKreachor picture KodeKreachor · Oct 10, 2012 · Viewed 41.3k times · Source

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
});

Answer

JBeagle picture JBeagle · Aug 12, 2013
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) {

});