86

ノックアウトで、新しい値を受け取る前に、オブザーバブルへのサブスクリプション内でオブザーバブルの現在の値を取得することは可能ですか?

例:

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

5 に答える 5

153
ko.subscribable.fn.subscribeChanged = function (callback) {
    var oldValue;
    this.subscribe(function (_oldValue) {
        oldValue = _oldValue;
    }, this, 'beforeChange');

    this.subscribe(function (newValue) {
        callback(newValue, oldValue);
    });
};

上記を次のように使用します。

MyViewModel.MyObservableProperty.subscribeChanged(function (newValue, oldValue) {

});
于 2013-08-12T09:49:54.960 に答える
88

次のような before 値へのサブスクリプションを行う方法があります。

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");
于 2012-10-10T16:24:27.087 に答える
3

以前の値を取得するために、書き込み可能な計算されたオブザーバブルから peek() を呼び出すことができることがわかりました。

このようなもの ( 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);
    }
});
于 2013-04-08T15:36:54.303 に答える