Reputation: 13099
I would like to bind the view model item to a part of HTML from collection which is bound to another HTML in the page.
Here is my sample HTML and JS code:
<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>
I want to bind the CategoryModel object to "divCategoryData" html section. As you can see, model is being passed to the click of row event. However, I am unable to display the category name & address on selection from the list.
Can someone guide me the code snippet of "self.onCategoryClick" event?
Upvotes: 1
Views: 143
Reputation: 8987
In your case I wouldn't try to rebind a div on each selection change.
I suggest to create an selectedCategory observable that contains the selected Category.
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());
See this fiddle for demo
I hope it helps.
Upvotes: 1