Reputation: 4328
I have a foreach
data-binding on an array.
I want to access the current object or place in the computed observable (as it happens with the click
data-binding).
Example:
Here is my View:
<tbody data-bind='foreach: items'>
<tr data-bind="attr: {class:$root.changeClass()}">
<td data-bind='text: name'></td>
</tr>
</tbody>
And, here is the view-model:
function model() {
var self = this;
self.items = ko.observableArray(itemArray);
self.changeClass = ko.computed(function(data) {
//code that depends on data
return 'someClass';
});
};
I'm a beginner. Please help. Thanks in advance.
Upvotes: 0
Views: 555
Reputation: 6045
Try something like this
View:
<table data-bind='foreach: items'>
<tr data-bind="attr: {class:$root.changeClass($data)}">
<td data-bind='text: $data'></td>
</tr>
</table>
Css :
.classEven{
color:blue;
}
.classOdd{
color:red;
}
viewModel:
function model() {
var self = this;
self.items = ko.observableArray([1,2,3]);
self.changeClass =function(data) {
//code that depends on data
if(data%2) return 'classEven';
else return 'classOdd';
};
};
ko.applyBindings(new model()); // This makes Knockout get to work
working sample fiddle here
Upvotes: 1