ビュー モデル アイテムを、ページ内の別の HTML にバインドされているコレクションの HTML の一部にバインドしたいと考えています。
サンプルの HTML と JS コードは次のとおりです。
<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」イベントのコード スニペットを教えてもらえますか?