I have a table being created that looks like the following:
<table>
<thead>
<tr>
<th>Index</th>
<th>Last Name</th>
<th>First Name</th>
</tr>
</thead>
<tbody data-bind="foreach: $data">
<tr data-bind="css: rowClass">
<td data-bind="text: $index"></td>
<td data-bind="text: LName"></td>
<td data-bind="text: FName"></td>
</tr>
</tbody>
</table>
I am using the knowckout.mapping functionality to take my data from my controller in and encoding to json. My javascript is below.
<script type="text/javascript">
$(function () {
var viewModelJSON = ko.mapping.fromJSON('@Html.Raw(jsonData)');
viewModelJSON.rowClass = ko.computed(function () {
return 'success';
});
ko.applyBindings(viewModelJSON);
});
</script>
Everything was working great until I added the data-bind for css rowClass. I’m simply trying to return the success class and but the javascript console reports “Unable to parse bindings” and “rowClass is not defined”. I’ve also tried declaring the rowClass function like:
viewModelJSON.rowClass = ko.computed(function () {
return 'success';
}, viewModelJSON);
But still with no luck. Any thoughts on what I’m doing wrong?
Working Solution
Updating my JavaScript seems to have solved my problem:
<script type="text/javascript">
$(function () {
var mapping = {
create: function (options) {
return new myImportItem(options.data);
}
}
var myImportItem = function (data) {
ko.mapping.fromJS(data, {}, this);
this.rowClass = ko.computed(function () {
return 'success';
}, this);
}
var viewModelJSON = ko.mapping.fromJSON('@Html.Raw(jsonData)', mapping);
ko.applyBindings(viewModelJSON);
});
</script>
Where you are adding the
cssbinding, the context will be an item in your array. However, you have placed therowClasscomputed at your root level.If you want to bind against it you would have to do it like
css: $parent.rowClassorcss: $root.rowClass(they would be the same in this case).If you want each item in your array to have a
rowClasscomputed, then you would want to look at using the mapping plugin’s mapping options.