태그 보관물: observable

observable

동일한 옵저버 블 구독에서 옵저버 블의 이전 값 가져 오기 구독 내에서 Observable의 현재 값을 얻을

새로운 값을 받기 전에 해당 Observable에 대한 구독 내에서 Observable의 현재 값을 얻을 수 있습니까?

예:

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



답변

다음과 같이 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");


답변

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

});


답변

Beagle90 답변에 약간의 변화가 있습니다. 예를 들어 dispose ()에 액세스 할 수 있도록 항상 구독 자체를 반환합니다.

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


답변

이 기능을 추가 하는 풀 요청 에는 beforeChange이벤트 사용에 의존하는 것보다 더 나은 몇 가지 다른 코드가 있습니다.

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

Michael을 인용하려면 :

나는 원래 beforeChange 문제를 해결하기 위해 을 했지만 항상 신뢰할 수있는 것은 아니라는 것을 깨달았습니다 (예 : valueHasMutated()Observable 을 호출 하는 경우).


답변

쓰기 가능한 계산 된 Observable에서 peek ()를 호출하여 before 값을 얻을 수 있음을 발견했습니다.

다음과 같은 것 ( 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);
    }
});


답변