You need to add active
as part of each object and make it observable, then pass it to the function: JsFiddle
The Html part:
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: name, css: $root.styling($data), click: function () { $root.toggle($data);}"> </span>
</li>
</ul>
And the ViewModel:
function AppViewModel() {
var self = this;
self.people = ko.observableArray([
{ name: 'Bert', active: ko.observable(false) },
{ name: 'Charles', active: ko.observable(false) },
{ name: 'Denise', active:ko.observable(false) }
]);
self.styling =function (person) {
if (person.active() === true) {
return 'test';
}
else {
return '';
}
};
self.toggle = function (person) {
person.active(!person.active());
}
}
ko.applyBindings(new AppViewModel());