2014-01-10 27 views
0

我想創建一個淘汰賽設置,允許用戶選擇一個列表的子集到另一個列表。我選擇第一個列表中的項目使用jQuery UI可選。當選擇運行時,我將所選項目的數據推送到第二個可觀察數組中。我有一個綁定到第二個數組的標籤,但是當我進行推送時,它似乎沒有更新。敲除:選擇一個數組的子集

這裏是我的代碼

<html> 
<head> 
<title>Sample</title> 
<link rel="stylesheet" href="jquery-ui-1.10.3.custom/css/ui-lightness/jquery-ui-1.10.3.custom.min.css"></link> 
<style> 
.ui-selected 
{ 
    border: 1px dotted red; 
} 
</style> 
<script type="text/javascript" src="knockout-2.3.0rc.js"></script> 
<script type="text/javascript" src="jquery-1.10.2.js"></script> 
<script type="text/javascript" src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script> 
<script type="text/javascript"> 
    function init() 
    { 
     function AppViewModel() 
     { 
      this.cars = ko.observableArray(
      [ 
       {year: 2004, make: "Chevy", model: "Malibu"}, 
       {year: 1995, make: "Honda", model: "Civic"}, 
       {year: 2004, make: "Chevy", model: "Malibu"}, 
       {year: 1985, make: "Honda", model: "Civic"},     
       {year: 1984, make: "Chevy", model: "Malibu"}, 
       {year: 1960, make: "Ford", model: "Ram"} 

      ]); 
      this.selectedCars = ko.observableArray(); 
      this.test=ko.observable("Bob"); 
     }  
     ko.applyBindings(new AppViewModel()); 
     $("#cars tbody").selectable(
     { 
      filter: "tr", 
      selected: function(event, ui) 
      { 
       var selectedCarRow = ui.selected; 
       var bindingContext = ko.contextFor(selectedCarRow); 
       var observableCarData = ko.dataFor(selectedCarRow); 
       bindingContext.$parent.selectedCars().push(observableCarData.make); 
       //alert(bindingContext.$parent.selectedCars().length); 
       //alert(bindingContext.$parent.test());        
      } 
     }); 
    } 
</script> 
</head> 
<body onload="init()"> 

<table id="cars"> 
    <thead><tr><th>Year</th><th>Make</th><th>Model</th></tr></thead> 
    <tbody data-bind="foreach: cars"> 
     <tr> 
      <td data-bind="text:year"></td> 
      <td data-bind="text:make"></td> 
      <td data-bind="text:model"></td> 
     </tr> 
    </tbody> 
</table> 
<ul data-bind="foreach:selectedCars"> 
    <li data-bind="text:$data"></li> 
</ul> 
    <pre data-bind="text: ko.toJSON($data, null, 2)"></pre> 
</body> 
</html> 

回答

2

對於你的代碼是正確的大部分。雖然有一個小問題。在可選的selected函數中,您編寫了bindingContext.$parent.selectedCars().push這會將對象推入標準數組而不是可觀察數組。要推入可觀察數組,這些更改將觸發淘汰賽事件,您將丟棄數組對象上的()

bindingContext.$parent.selectedCars.push(observableCarData.make); 

例小提琴:http://jsfiddle.net/n27QL/1/