Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Advanced" knockout css binding statement doesn't behave exactly as expected

I have a rather lengthy knockout css binding applied to an <li> element.

Under the right scenario in my view model, the class list could look like this:

<li class="workItem task notRead">
</li>

where "workItem" is just a static string, "task" is returned from the "workItemTypeName" computed in my view model and "notRead" is toggled based on properties in my view model.

In the perfect world that exists in my head, I would have been able to combine these three class assignment statements (which work individually):

<li class="workItem">
</li>

<li data-bind="css: workItemTypeName">
</li>

<li data-bind="css: { 'notRead': isNotRead }">
</li>

into something like this:

<li data-bind="css: { 'workItem', workItemTypeName, 'notRead': isNotRead }">
</li>

After some wrenching around, I managed to get to this (which works):

<li data-bind="attr: { 'class': workItemTypeName + ' ' + ' workItem' }, css: {
'notRead': isNotRead }">
</li>

But I just don't like it... Does anybody know if it's possible to combine static, computed and toggled statements into the same css binding? Or if it's something that has been asked and may be added to knockout in the future?

like image 734
Rob Avatar asked Feb 15 '23 17:02

Rob


1 Answers

While @ExplosionPills' solution goes into the right direction, it's still not idiomatic enough, IMHO.

Knockout expects an object of CSS class names and truthy/falsy values or observables (!) in the css binding. So just give it one.

self.workItemCss = ko.computed(function () {
    var classes = {};
    classes.workItem = true;
    classes.notRead = self.isNotRead;
    classes[ko.unwrap(self.workItemTypeName)] = true;
    return classes;
});

http://jsfiddle.net/SHmc8/ (interactive: http://jsfiddle.net/SHmc8/1/)


Note that you can also use the class attribute and the css binding together:

<li class="any fixed classes" data-bind="css: workItemCss">

so the classes.workItem = true; doesn't really make sense.

like image 149
Tomalak Avatar answered Mar 16 '23 00:03

Tomalak