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」事件的代碼片段?