Databinding class attribute
https://groups.google.com/d/topic/knockoutjs/l9qt-X_HGD0/discussion
HTML
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/knockout-latest.debug.js"></script>
<h2>Knockoutjs - learning steps</h2>
<p>Ways to set an css class based on the properties of the current item </p>
<table data-bind="template: { name: 'itemRowTemplate', foreach: players}">
<thead><tr><th>Firstname</th><th>Level</th><th>age</th></tr></thead>
</table>
<script id='itemRowTemplate' type='text/html'>
<tr data-bind="css:{slanted: age<18 }" >
<td data-bind='text: fname'></td>
<td data-bind="text: level"></td>
<td data-bind="text: age, css: { minor: age < 18 }"></td>
</tr>
</script>
<!--
using a computed function to return different values does not work
<td data-bind="text: getCssClass()"></td>
<td data-bind="text: getCssClass"></td>
-->
<hr>
<h3>Debug Information</h3>
<pre data-bind="text: JSON.stringify(ko.toJS($data), null, 2)"></pre>
<hr>
<div class="footnote">
styles copied from <a href="http://www.getskeleton.com/">skeleton</a>
</div>
CSS
h1, h2, h3 { color: #181818; font-family: "Georgia", "Times New Roman", Helvetica, Arial, sans-serif; font-weight: normal; }
h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { font-weight: inherit; }
h1 { font-size: 46px; line-height: 50px; margin-bottom: 14px;}
h2 { font-size: 35px; line-height: 40px; margin-bottom: 10px; }
h3 { font-size: 28px; line-height: 34px; margin-bottom: 8px; }
table { margin: 2em 1em 1em 3em; border: 1px solid #bada55;}
th { font-weight: bold;}
td, th {padding: 0.3ex 1ex;}
.slanted { font-style: italic; color:blue;}
.minor { color: red; font-weight: bold;}
.footnote {font-size: 12px; color: grey; padding: 1ex;}
JavaScript
var playerList = [];
playerList[0] = {fname: "Billy", level:"beginner", age: 20};
playerList[1] = {fname: "Jean", level:"intermediate", age: 22};
playerList[2] = {fname: "is not my lover", level:"advanced", age: 24};
playerList[3] = {fname: "Kid is not my son", level:"beginner", age: 17};
playerList[4] = {fname: "Beauty Queen", level:"intermediate", age: 24};
function MyViewModel() {
var self = this;
self.level = ko.observable("expert"),
self.players = ko.observableArray(playerList)
self.getCssClass = ko.computed(function() { return self.level + "foo";}); // return (self.age() < 18) : "foo" ? "bar" ;
}
ko.applyBindings(new MyViewModel());