Knockout - Row Selection
http://stackoverflow.com/questions/8838132/display-clicked-item-with-knockoutjs
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<div data-bind="if:model.CurrentDisplayThing">
Display: <span data-bind="text: model.CurrentDisplayThing().ID"></span>
</div>
<table class="defaultGrid">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: model.Things">
<tr data-bind="click: $root.selectThing, css: { selected: isSelected} ">
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
</tr>
</tbody>
</table>
CSS
.selected { background-color: yellow; }
thead tr {
border:1px solid black;
background:lightgray;
}tbody tr {
border:1px solid black;
cursor: pointer;
}
JavaScript
$(function() {
Thing = function(id, name, selected) {
var self = this;
self.ID = id,
self.Name = name,
self.isSelected = ko.computed(function() {
return selected() === self;
});
};
function viewModel() {
var self = this;
self.model = {};
self.model.CurrentDisplayThing = ko.observable();
self.model.Things = ko.observableArray(
[
new Thing(1, "Thing 1", self.model.CurrentDisplayThing),
new Thing(2, "Thing 2", self.model.CurrentDisplayThing),
new Thing(3, "Thing 3", self.model.CurrentDisplayThing)
]);
self.selectThing = function(item) {
self.model.CurrentDisplayThing(item);
};
}
ko.applyBindings(new viewModel());
});