Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change table row background color from KO's binding method?

I'm using KO.js to bind a table body with many rows. The first column has some buttons, if user clicks on a button of a row, I want that row be highlighted. But I don't know how to reference to the table row from Ko's binding method.

here's the fiddle I'm talking about.

and some code:

<table class="table table-bordered">
    <tbody data-bind="foreach: frameworks">
        <td>
            <button class=btn data-bind="click: $parent.doStuff">A</button>
        </td>
        <td data-bind="text: $data"></td>
    </tbody>
</table>


var App = new function () {
        var self = this;
        self.frameworks = ko.observableArray();
        self.doStuff = function () {
            //how to change table row color?
        };
    };

App.frameworks.push('bootstrap');
App.frameworks.push('knockout.js');
ko.applyBindings(App);
like image 274
Ray Cheng Avatar asked Feb 17 '23 11:02

Ray Cheng


1 Answers

You are close. I have updated your fiddle here with the solution.

HTML

<table class="table table-bordered">
    <tbody data-bind="foreach: frameworks">
        <tr data-bind="css: {'selected':$root.selectedItem() == $data}">
            <td>
                <button class=btn data-bind="click: $root.doStuff">A</button>
            </td>
            <td data-bind="text: $data"></td>
        </tr>
    </tbody>
</table>

CSS

.selected
{
    background-color:red;
}

Javascript

    var App = new function () {
        var self = this;
        self.frameworks = ko.observableArray();
        self.selectedItem = ko.observable(null);
        self.doStuff = function (item) {
            self.selectedItem(item);
            //do other things here for the button click
        };
    };

    App.frameworks.push('bootstrap');
    App.frameworks.push('knockout.js');
    ko.applyBindings(App);
like image 178
RodneyTrotter Avatar answered Feb 19 '23 04:02

RodneyTrotter