2013-02-28 5 views
6

관찰 가능 값 수정을 거부하거나 취소하는 방법이 있습니까? 이처럼 :관찰 가능 값 변경 거부

observable.subscribe (function (newvalue) { 
    if (newvalue < 0) { 

     // cancel changing 
    } 
    else{ 
     // proceed with change 
    } 

}, this) 

답변

8

편집 : 나는 다른 무언가를 발견

: 쓰기 가능한 계산 관찰 가능한.

function AppViewModel() { 
    this.field = ko.observable("initValue"); 
    this.computedField = ko.computed({ 
     read: function() { 
      return this.field(); 
     }, 
     write: function (value) { 
      if(value > 0) { 
       this.field(value); 
      } 
     }, 
     owner: this 
    }); 
} 

그럼 당신이 계산 된 필드에 바인딩 : 여기

은 예입니다.

/편집

맞춤 바인딩이 필요합니다. 문서 여기 http://learn.knockoutjs.com/#/?tutorial=custombindings

되거나 : 여기

바인딩 정의에 대한 튜토리얼입니다 http://knockoutjs.com/documentation/custom-bindings.html

나는 다음과 같은 사용 쓰기 값을 거부 할 수 있도록하려면
0

:

  • 가이 관찰 숨겨진 만들기 그 값을 저장합니다.
  • 숨겨진 관찰 가능 정보를 기반으로 쓰기 가능한 계산 된 관찰 가능을 반환합니다.
  • 계산 된 관찰 가능 항목에 무언가가 기록되면이를 수락하기 전에 유효성을 검사하십시오.

는이 코드에 넉 아웃 연장 :

ko.conditionedObservable = function (initialValue, condition) { 
    var obi = ko.observable(initialValue); 
    var computer = ko.computed({ 
     read: function() { return obi(); }, 
     write: function (newValue) { 
      //unwrap value - just to be sure 
      var v = ko.unwrap(newValue); 
      //check condition 
      if (condition(v)) { 
       //set it to the observable 
       obi(v); 
      } 
      else { 
       //reset the value 
       computer.notifySubscribers(); 
      } 
     } 
    }); 
    return computer; 
}; 

이 같은 목적에 사용 :

field = ko.conditionedObservable<number>(null, (v) => parseInt(v) > 0); 

더 설명은 내 Conditioning Knockout Observables: reject values 블로그를 확인합니다.