Reputation: 5143
I need to change the tr
background-color
when mouse is clicked over it. I bind the click
event using knockout because i need to update my viewmodel when user clicks over each table row.
I'd need to call $(row).css('background-color', 'red');
inside my viewmodel.
demo: http://jsfiddle.net/tzD4T/391/
My view model:
function ViewModelTrazas(data) {
var self = this;
self.trazas = ko.observableArray();
array = self.trazas;
self.selectRow = function (row) {
self.seletedRow(row);
// HERE I SHOULD CHANGE THE TR BG
// SOMETHIN LIKE THIS:
// $(row).css('background-color', 'red');
}
self.seletedRow = ko.observable();
}
The html:
<div id="gridAndDetail">
<table style="width: 100%">
<tr>
<td>
<div style="margin-top:-4px;
height: 200px; overflow:auto;">
<table id="datagrid" style="width: 100%;">
<thead style="text-align:left">
<tr>
<th>Date</th>
<th>Machine</th>
<th>Event type</th>
<th>Detail</th>
</tr>
</thead>
<tbody data-bind="foreach: trazas">
<tr data-bind="click: $parent.selectRow">
<td data-bind=" text: Fecha"></td>
<td data-bind=" text: Maquina"></td>
<td data-bind=" text: TipoEvento"></td>
<td data-bind=" text: Mensaje"></td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</table>
(using jquery click
event binder should do the job but I don't know why I'm not able to select all my tr
using this selector:
$('#datagrid tr').click(function(){});
It only matches the thead
section of the table.)
Upvotes: 1
Views: 1198
Reputation: 139778
If you are using Knockout trying to solve things with jQuery should not be your first choose.
The more KO way if doing this is to define a css class like red and toggle that css class with the css
binding depending on the selection:
.red {
background-color: red;
}
And in your viewmodel:
<tr data-bind="click: $parent.selectRow,
css: {red: $parent.seletedRow() == $data}">
Demo JSFiddle.
An alternative approach would be to a have an isSelected
property on your individual items. Then you can set isSelected
property in your selectRow
handler and use this new isSelected
in your css binding instead of the parents $parent.seletedRow() == $data
expression.
Upvotes: 2