I know that you can use knockout to set the class as per a function return like so;
<span data-bind="css: styling()"></span>
You can also set them inline with a true/false value.
<span data-bind="css: {className: $parent.active() == $data}"></span>
Is there a way to do both in the one binding? My example is that I want to return a custom class depending on the type of the item displayed by the span element (there will be many of these) but I also want them to be highlighted if they are selected.
It seems that you cannot use functions on the right hand side of the object, and having two cause the second to overwrite the first.
Any ideas?
I know that you can use knockout to set the class as per a function return like so;
<span data-bind="css: styling()"></span>
You can also set them inline with a true/false value.
<span data-bind="css: {className: $parent.active() == $data}"></span>
Is there a way to do both in the one binding? My example is that I want to return a custom class depending on the type of the item displayed by the span element (there will be many of these) but I also want them to be highlighted if they are selected.
It seems that you cannot use functions on the right hand side of the object, and having two cause the second to overwrite the first.
Any ideas?
Share Improve this question asked Aug 20, 2013 at 8:59 ShadowShadow 9,4474 gold badges49 silver badges59 bronze badges1 Answer
Reset to default 6With this sample you will be able to specify the classes of each item.
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 fiddle
Edit:
@Shadow : You right, if you pass a value to a puted it is to set (or write) it.
I think this would match your needs. When on an item the toggle function is called. Then the active observable will be changed and finally the styling puted.
JS
var Item = function(data) {
var self = this;
self.name = data;
self.active = ko.observable(false);
self.styling = ko.puted(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 fiddle