CSS knockout style with function as well as binding

I know that you can use knockout to set the class according to the function return;

<span data-bind="css: styling()"></span> 

You can also set them in a string with true / false value.

 <span data-bind="css: {className: $parent.active() == $data}"></span> 

Is there a way to do this as in a single binding? In my example, I want to return a custom class depending on the type of element displayed by the span element (there will be many of them), but I also want them to be selected if they are selected.

It seems that you cannot use the functions on the right side of the object and have two reasons for the second to overwrite the first.

Any ideas?

+4
source share
1 answer

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

+6
source

Source: https://habr.com/ru/post/1497954/


All Articles