With this example, you can specify the classes of each element.
View
<div data-bind="foreach: items" > <span data-bind="css : $parent.styling($data), text: $data"></span> </div>
JS:
var vm = { items : ['a','b','c' ], styling : function(item ) { if(item =='a') return 'active'; if(item =='b') return 'active bold'; return ''; } }; ko.applyBindings(vm);
See violin
Edit:
@Shadow: you're right if you pass the value to the calculated one to set (or write) it.
I think that would suit your needs. When the switch function is called on an element. Then the active observable will be changed and, finally, the style will be calculated.
Js
var Item = function(data) { var self = this; self.name = data; self.active = ko.observable(false); self.styling = ko.computed(function(item ) { if(self.active()) return 'active'; return ''; }); self.toggle = function(){ self.active(!self.active()); } }; var vm = { items : [new Item('a'),new Item('b'), new Item('c') ] }; ko.applyBindings(vm);
View
<div data-bind="foreach: items" > <span data-bind="css : styling, text: name, click : toggle"></span> <br/> </div>
See violin
source share