Reputation: 11673
I'm trying to learn Knockout. I want to highlight a table row when clicking on an link within the row. I'm having a hard time understanding the context of this
, e
and how knockout interacts with JQuery
. Can I not build knockout functions just as standard jquery functions?
<table>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Cat</th>
<th>Size</th>
</tr>
</thead>
<tbody data-bind="foreach: components">
<tr>
<td></td>
<td><a data-bind="text: Name, click: $parent.highlightComponent" href="#"></a></td>
<td data-bind="text: Category"></td>
<td data-bind="text: Size"></td>
</tr>
</tbody>
</table>
And then my view model...
function MyViewModel() {
this.components = ko.observableArray();
this.selectedComponent = ko.observable();
this.highlightComponent = function(e) {
console.log($(this).parents("tr"));
$(this).closest("tr").siblings().removeClass("diffColor");
$(this).parents("tr").toggleClass("diffColor", e.clicked);
}
}
Upvotes: 3
Views: 2748
Reputation: 49095
Add an IsHighlighted
property on each item in the components
array to indicate whether the item is highlighted:
this.IsHighlighted = ko.observable(false);
Then in your HTML, turn on that property upon click
and have your TR.diffColor
class bound to that property:
<tbody data-bind="foreach: components">
<tr data-bind="css: { diffColor: IsHighlighted }">
<td></td>
<td><a data-bind="text: Name, click: IsHighlighted" href="#"></a></td>
<td data-bind="text: Category"></td>
<td data-bind="text: Size"></td>
</tr>
</tbody>
Update:
As per your request to only allow one highlighted item at a time, try to add HighlightedRowIndex
observable to the root view-model:
this.HighlightedRowIndex = ko.observable();
And in your HTML:
<tbody data-bind="foreach: components">
<tr data-bind="css: { diffColor: $root.HighlightedRowIndex() == $index }">
<td></td>
<td><a data-bind="text: Name, click: $root.HighlightedRowIndex.bind(null, $index)" href="#"></a></td>
<td data-bind="text: Category"></td>
<td data-bind="text: Size"></td>
</tr>
</tbody>
Upvotes: 5