Get previous value of an observable in subscribe of same observable

前端 未结 5 1530
抹茶落季
抹茶落季 2020-12-07 15:22

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:

<         


        
相关标签:
5条回答
  • 2020-12-07 16:03

    The pull request to add this feature has some different code that winds up being better than relying on using the beforeChange event.

    All credit for the solution to Michael Best

    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 suggested using beforeChange to solve this problem but have since realized that it's not always reliable (for example, if you call valueHasMutated() on the observable).

    0 讨论(0)
  • 2020-12-07 16:03

    I have found that I can call peek() from a writable computed observable 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);
        }
    });
    
    0 讨论(0)
  • 2020-12-07 16:04

    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;
    };
    
    0 讨论(0)
  • 2020-12-07 16:07
    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) {
    
    });
    
    0 讨论(0)
  • 2020-12-07 16:10

    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");
    
    0 讨论(0)
提交回复
热议问题