2012-10-16 2 views
1

knockout js로이 시나리오를 모델링 할 수 있습니까?knockout js 쉽게 모델링 할 수 있습니다

Current Income :

내가 3 개 필드가 말해 나는이 값을 변경하면 Retirement Income 필요 (Current Income * Percentage of Current Income)/100

Retirement Income으로 업데이트 :이 값을 변경하면 Percentage of Current Income 필요 (Retirement Income/Current Income) * 100

로 업데이트 Percentage of Current Income :이 값을 변경하면

로 업데이트해야합니다.

이것은 순환 의존성입니까? 녹아웃 js를 사용하여 모델링 할 수 있습니까? 나는 모든 필드를 계산할 필요가 있다고 가정하고 싶지만, 기본값을 설정하는 방법이나 아직 선언되지 않은 계산 된 관측 값을 사용하는 방법을 모르겠습니다.

jsfiddle 출발점 : http://jsfiddle.net/LkqTU/4482/

답변

2

당신은 read/write computed를 사용할 수 있습니다

다음
var ViewModel = function() { 
    var self = this; 

    self.currentIncome = ko.observable(1000); 
    self.currentIncomePercent = ko.observable(5); 

    self.retirementIncome = ko.computed({ 
     read: function() { 
      var result = self.currentIncome() * self.currentIncomePercent()/100; 
      return result.toFixed(2); 
     }, 
     write: function(value) { 
      var result = value/self.currentIncome() * 100; 
      self.currentIncomePercent(result.toFixed(2)); 
     } 
    }); 
}; 

ko.applyBindings(new ViewModel()); 

하는 노력 바이올린 : http://jsfiddle.net/vyshniakov/LkqTU/4503/

+0

감사합니다 ... 영리하고 그것을 할 우아한 방법. – woggles

관련 문제