2017-04-26 71 views
0
結合

請這個簡單的代碼來說明情況:knockoutjs在運行時改變

<select id="se"> 
    <option value="0">EN</option> 
    <option value="1">FR</option> 
    <option value="2">AR</option> 
    <option value="3">SP</option> 
</select> 
<input id="inp" data-bind='textInput: DESCRIPTION_FR' /> 


<script src="../Scripts/jquery-1.9.1.min.js"></script> 
<script src="../Scripts/knockout-3.4.0.js"></script> 

<script type="text/javascript"> 
    var PRDVM = function() { 
     var self = this; 
     self.ID = ko.observable(0); 
     self.DESCRIPTION_FR = ko.observable('FR'); 
     self.DESCRIPTION_EN = ko.observable('EN'); 
     self.DESCRIPTION_AR = ko.observable('AR'); 
     self.DESCRIPTION_SP = ko.observable('SP'); 
     self.IMAGE = ko.observable('/images/noimage.png'); 
}; 
ko.applyBindings(new PRDVM()); 
</script> 

我想是通過改變屬性在運行時輸入的結合,通過改變下拉列表切換語言選擇

任何關於如何做的想法都會很棒。

這裏出發小提琴 https://https://jsfiddle.net/smtsghqm/2/

感謝。

回答

2

您可以嘗試使用可寫計算屬性,該屬性根據所選選項確定要顯示/更新哪些可觀察值。綁定應該是計算出來的,不需要改變。

var PRDVM = function() { 
 
    var self = this; 
 
    self.SelectedValue = ko.observable(); 
 
    self.ID = ko.observable(0); 
 
    self.DESCRIPTION_FR = ko.observable('FR'); 
 
    self.DESCRIPTION_EN = ko.observable('EN'); 
 
    self.IMAGE = ko.observable('/images/noimage.png'); 
 
    
 
    self.DESCRIPTION = ko.computed({ 
 
     read: function(){ 
 
      switch(self.SelectedValue()){ 
 
       case "0": 
 
      \t   return self.DESCRIPTION_EN(); 
 
       case "1": 
 
      \t   return self.DESCRIPTION_FR(); 
 
      } 
 
     }, 
 
     write: function(value){ 
 
      switch(self.SelectedValue()){ 
 
       case "0": 
 
      \t   self.DESCRIPTION_EN(value); 
 
      \t   break; 
 
       case "1": 
 
      \t   self.DESCRIPTION_FR(value); 
 
      \t   break; 
 
      } 
 
     } 
 
    }) 
 
}; 
 
ko.applyBindings(new PRDVM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 

 
<select id="se" data-bind="value: SelectedValue"> 
 
    <option value="0">EN</option> 
 
    <option value="1">FR</option> 
 
    <option value="2">AR</option> 
 
    <option value="3">SP</option> 
 
</select> 
 
<br /><br /><br /> 
 
    <input id="inp" data-bind='textInput: DESCRIPTION' />