2013-03-13 20 views
0

我有以下的業務需求較大:淘汰賽JS確保一個值比另一個

有2個文本框,其中用戶需要輸入他們目前的年齡和退休年齡。 退休年齡需要大於當前年齡,因此如果用戶輸入的退休年齡小於當前年齡,則應將退休年齡更新爲當前年齡,並且如果用戶輸入的當前年齡大於當前年齡退休年齡,那麼退休年齡必須設定爲當前年齡。

有沒有一種簡單的方法來使用knockout js來做到這一點?我假設我需要一個具有某種後備存儲的兩個字段的計算可觀察值?

繼承人我的出發點:http://jsfiddle.net/RVNHy/

JS:

var viewModel = function() { 
    this.currentAge= ko.observable(32); 
    this.retirementAge = ko.observable(44); 
}; 

ko.applyBindings(new viewModel()); 

HTML:

<div class='liveExample'> 
    <p>Current Age: <input data-bind='value: currentAge' /></p> 
    <p>Retirement Age: <input data-bind='value: retirementAge' /></p> 
</div> 

回答

1

是啊,這是你想要什麼:

function MyViewModel() { 
    var self = this; 
    var age= ko.observable(32); 
    var retAge = ko.observable(44); 

    self.currentAge = ko.computed({ 
     read: function() { 
      return age(); 
     }, 
     write: function (value) { 
      retAge(Math.max(value, retAge)); 
      age(value); 
     }, 
     owner: this 
    }); 
} 

,做小號ame創建退休年齡的計算可觀察值。

+0

很棒!謝謝 – woggles 2013-03-13 10:36:34