Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout: Selectable table rows without extending the model?

Tags:

knockout.js

I have the following table template that is rendered through knockout:

            <table class="gv" data-bind="visible: products().length > 0">
                <thead>
                    <th>Type</th>
                    <th>Name</th>
                </thead>
                <tbody data-bind="foreach: products">
                    <tr data-bind="click: $root.selectProduct">
                        <td data-bind="text: type"></td>
                        <td data-bind="text: name"></td>
                    </tr>
                </tbody>
            </table>

Now I want to make the rows clickable and want to assign a css class if a row is selected. Only 1 (!) row could be selected at a time, so others have to be unchecked.

The simplest way would be to extend my model (product class) with a selected property but this would destroy my 1:1 mapping with the server side.

How should I solve this issue? How would you handle this?

like image 746
timmkrause Avatar asked Mar 26 '12 11:03

timmkrause


2 Answers

This was my final solution now, no extra hidden radio buttons:

<tr data-bind="click: $root.selectProduct, css: { 'active-row': $root.selectedProduct() === $data }">

And the selectedProduct implementation within the ViewModel:

function AppViewModel() {
    // Private
    var self = this;

    // Public Properties
    self.selectedProduct = ko.observable();
like image 197
timmkrause Avatar answered Nov 21 '22 19:11

timmkrause


You could add a hidden radio button group to the table, and when the row is selected calling selectProduct the radio button is selected.

This ensures that only one row is selected.

Alternatively you could write a custom binding using the jQuery .data() to specify the selected row.

like image 25
Darbio Avatar answered Nov 21 '22 19:11

Darbio