Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine dynamic and static classes through css binding, knockout.js

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?

like image 286
Artem Svirskyi Avatar asked Oct 08 '13 19:10

Artem Svirskyi


3 Answers

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 }

like image 180
Aleksey Avatar answered Oct 23 '22 04:10

Aleksey


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.

like image 14
Simon_Weaver Avatar answered Oct 23 '22 05:10

Simon_Weaver


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/

like image 4
Matt Burland Avatar answered Oct 23 '22 04:10

Matt Burland