Skip to content
mbest edited this page Dec 20, 2011 · 4 revisions

This binding allows you set an arbitrary css class for an element. It requires jQuery.

ko.bindingHandlers['class'] = {
    'update': function(element, valueAccessor) {
        if (element['__ko__previousClassValue__']) {
            $(element).removeClass(element['__ko__previousClassValue__']);
        }
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).addClass(value);
        element['__ko__previousClassValue__'] = value;
    }
};

Here's an alternate version that uses Knockout only (no jQuery):

ko.bindingHandlers['class'] = {
    'update': function(element, valueAccessor) {
        if (element['__ko__previousClassValue__']) {
            ko.utils.toggleDomNodeCssClass(element, element['__ko__previousClassValue__'], false);
        }
        var value = ko.utils.unwrapObservable(valueAccessor());
        ko.utils.toggleDomNodeCssClass(element, value, true);
        element['__ko__previousClassValue__'] = value;
    }
};

Example:

<table>
    <tbody data-bind="foreach: datasets">
        <tr data-bind="class: rowClass">
            <td data-bind="text: title"></td>
            <td data-bind="text: dataCount"></td>
        </tr>
    </tbody>
</table>

Here's a demonstation fiddle and an expanded fiddle comparing it to attr (thanks Koviko).

Clone this wiki locally