2012-03-05 67 views
0

我想將選擇與KnockoutJS綁定到來自我的模型的預定義值。根據文檔,這應該來自屬性,但我不能預先選擇基於此的下拉列表中的值。下面是示例代碼,反映了我的問題:KnockoutJS選擇查找

<script src="Scripts/jquery-1.7.1.js"></script> 
<script src="Scripts/knockout-2.0.0.js"></script> 

<script> 
    $(function() { 

     var viewModel = 
     { 
      Positions: ko.observableArray(
              [ 
               { Id: 1, PositionName: 'Point Guard' }, 
               { Id: 2, PositionName: 'Shooting Guard' }, 
               { Id: 3, PositionName: 'Center' }, 
               { Id: 4, PositionName: 'Small Forward' }, 
               { Id: 5, PositionName: 'Power Forward' } 
              ]), 
      Players: ko.observableArray(
              [ 
               { Id: 1, Name: 'Derrick Fisher', Position: 'Point Guard' }, 
               { Id: 2, Name: 'Kobe Bryant', Position: 'Shooting Guard' }, 
               { Id: 3, Name: 'Andrew Bynum', Position: 'Center' }, 
               { Id: 4, Name: 'Metta World Peace', Position: 'Small Forward' }, 
               { Id: 5, Name: 'Pau Gasol', Position: 'Power Forward' } 
              ]) 
     }; 

     ko.applyBindings(viewModel); 

    }); 
</script> 

在我的綁定我想用一個簡單的表格,其中第一列已經預選查找值,在這種情況下,玩家的「位置」默認。這裏有一個例子:

<table> 
    <thead> 
     <tr> 
      <td>Position</td> 
      <td>Player</td> 
     </tr> 
    </thead> 
    <tbody data-bind='foreach: Players'> 
     <tr> 
      <td> 
       <select data-bind="options: $root.Positions, optionsText:'PositionName', 
           value:'$data.Position', optionsCaption: 'Choose...'"> 
       </select> 
      </td> 
      <td> 
       <span data-bind='text: Name'></span>         
      </td> 
     </tr> 
    </tbody> 
</table> 

的查找似乎綁定好(選擇填充在查找所有的位置值),但是給定的玩家的位置不被默認選中。任何人都可以發現我做出了錯誤的假設或錯誤嗎?

回答

1

當您不使用optionsValue時,它會將選定的對象寫入您綁定的內容value

如果您的player有一個position對象的單獨副本,那麼它將不匹配。

例如,

var a = { Id: 3, Name: 'Andrew Bynum', Position: 'Center' }; 
var b = { Id: 3, Name: 'Andrew Bynum', Position: 'Center' }; 

alert(a === b); //false they are not a reference to the same object 

所以,你的玩家要麼需要使用引用同一對象,或者您應該指定optionsValueId結合,所以它讀取/寫入標識玩家的位置屬性。

+0

謝謝你的幫忙!我試圖在http://knockoutjs.com/documentation/options-binding.html去掉例子4,但在這種情況下你是對的,只需綁定optionsValue – t3rse 2012-03-06 15:43:44