2013-10-14 51 views
1

我想將視圖模型項綁定到頁面中另一個HTML綁定的集合中的HTML部分。
這是我的樣品HTML和JS代碼:無法使用Knockout綁定來自集合的視圖模型

<div> 
<div style="width: 200px; float: left;" class="roundedBorder"> 
    <fieldset id="fieldsetCategory"> 
     <legend>Category</legend> 
     <table> 
      <thead> 
       <tr> 
        <th>Category Name</th>  
       </tr>  
      </thead> 
      <tbody data-bind="foreach: categories"> 
       <tr data-bind="click: onCategoryClick.bind($data, $parent)"> 
        <td data-bind="text: name"></td> 
       </tr> 
      </tbody> 
     </table> 
    </fieldset> 
</div> 
<div id="divCategoryData" style="width: 200px; float: right;" class="roundedBorder"> 
    <fieldset id="fieldsetCategoryInfo"> 
     <legend>Category Information</legend> 
     <table> 
      <tr> 
       <td>Catgory Name:</td> 
       <td> 
        <strong data-bind="text: name"></strong> 
       </td> 
      </tr> 
      <tr> 
       <td>Catgory Address:</td> 
       <td> 
        <strong data-bind="text: address"></strong> 
       </td> 
      </tr> 
     </table> 
    </fieldset> 
</div> 

<script type="text/javascript"> 
    function CategoryModel(name, address) { 
     var self = this; 
     this.name = name; 
     this.address = address; 
    } 

    function CategoryViewModel() { 
     var self = this; 
     self.categories = [ 
      new CategoryModel("Category 1", "Delhi"), 
      new CategoryModel("Category 2", "Gurgaon"), 
      new CategoryModel("Category 3", "Noida"), 
      new CategoryModel("Category 4", "Ghaziabad") 
     ]; 
    } 

    self.onCategoryClick = function() { 
     var model = this; 
     alert(model.name + " " + model.address); 
     ko.applyBindings(model, "divCategoryData"); 

    }; 

    $(document).ready(function() { 
     ko.applyBindings(new CategoryViewModel()); 
     ko.applyBindings(new CategoryModel(), "divCategoryData"); 
    }); 

</script> 

我想將CategoryModel對象綁定到 「divCategoryData」 HTML部分。正如你所看到的,模型正被傳遞給點擊行事件。但是,我無法在列表中顯示選擇的類別名稱&地址。
有人可以指導我的「self.onCategoryClick」事件的代碼片段?

回答

1

在你的情況下,我不會嘗試重新綁定每個選擇更改的div。

我建議創建一個包含所選類別的selectedCategory observable。

function CategoryModel(name, address) { 
    var self = this; 
    this.name = name; 
    this.address = address; 
} 

function CategoryViewModel() { 
    var self = this; 
    self.categories = [ 
    new CategoryModel("Category 1", "Delhi"), 
    new CategoryModel("Category 2", "Gurgaon"), 
    new CategoryModel("Category 3", "Noida"), 
    new CategoryModel("Category 4", "Ghaziabad")]; 

    self.selectedCategory = ko.observable(); 

    self.onCategoryClick = function (model) { 
     //alert(model.name + " " + model.address); 
     self.selectedCategory(model); 

    }; 
} 

ko.applyBindings(new CategoryViewModel()); 

用於演示

我希望它可以幫助見this fiddle

相關問題