In knockout.js we can use css binding for static classes
<div data-bind="css: {'translucent ': number() < 10}">static dynamic css classes</div>
and dynamic
<div data-bind="css: color">static dynamic css classes</div>
I've tried http://jsfiddle.net/tT9PK/1/ to combine it in something like
css: {color, translucent: number() < 10}
to get dynamic class color
and static translucent
at the same time, but I get an error. Is there a way to do that?
You can add dynamic class by css
property and then add static class by attr
property
<div data-bind="attr: { 'class': color }, css: { 'translucent': number() < 10 }">
static dynamic css classes
</div>
Be sure to add any predefined classes to this binding
attr: { 'class': color }
I solved this problem a while back by just cloning the css
binding as css2
.
ko.bindingHandlers['css2'] = ko.bindingHandlers.css;
Normally you can't use the same binding handler twice in a data-bind attribute, so this allowed me to do the following:
<div data-bind="css: color, css2: { 'translucent': number() < 10 }">static dynamic css classes</div>
I can't quite decide whether I still prefer this, or @Aleksey's answer, but this may be the only choice if you have multiple dynamic classes to add.
Your best bet is probably not to combine them. Instead use a computed property of your view model to combine them into a single property that you can bind dynamically. That way you can also avoid putting logic in your view with the number() < 10 binding, which is cleaner anyway.
Like this, for example:
viewModel.colorAndTrans = ko.computed(function () {
var cssString = viewModel.color();
if (viewModel.number() < 10) {
cssString += " translucent"
}
return cssString;
});
See this working example: http://jsfiddle.net/tT9PK/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With