Knockoutjs css not working

(Using KnockoutJs 2.0.0)

I have a list of phone numbers in my view model. Each phone number has a type (home, work, mobile, etc.). I want an icon (based on the font class) to be displayed next to each phone number.

If I hardcode the icons in the css binding, everything works:

<tbody data-binding="foreach: phoneList">
    <tr>
       <td><span data-bind="css: {'icon-home' : TypeId() == 1, 'icon-building': TypeId() == 2, ... , 'icon-phone': TypeId() >= 7></span></td>
    ...
</tbody>

I wanted to replace the hardcoded list with a function call. At first I tried to add the function to the parent, but was not successful, so I tried to add the function directly to the phone object as a function and how ko.computed(), but none of them work for me.

I came up with the code here that demonstrates the problem. If you check the span element of table elements, you will almost see it as if waiting for the data processes the returned string as an array of characters and sets the class based on indexes, rather than treating the returned string as a class.

I am sure that this is something completely obvious, but I beat my head to no avail.

+4
source share
3 answers

The calculated observable should work fine. The problem is that you are returning from what is computed by the observable. You need to return the class definition in the same format as the hard-coded version:

me.getClass = ko.computed(function() {
    return me.typeId() == 1 ? { 'mobile': true } : { 'business': true };
});

: http://plnkr.co/edit/qDjgMlZpXHjn5ixY3OCt

, , , . , , Knockout 3.0.0, .

:

ko.bindingHandlers.setClass = {
    update: function(element, valueAccessor, allBindings) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        element.className = value;
    }
};

me.setClass = ko.computed(function() {
    return me.typeId() == 1 ? "mobile" : "business";
});

HTML:

<td data-bind="setClass: setClass, text: typeId"></td>

, , : http://plnkr.co/edit/ryaA4mIf7oh5Biu8bKj0?p=info

+1

Fix

KO 3.0.

ko.computed getClass:

me.getClass = ko.computed(function() { return me.typeId == 1 ? "mobile" : "business"; });

me.getClass = ko.computed(function() { return this.typeId() == 1 ? "mobile" : "business"; }, me);

, KO 2.0, . , , .

+1

An alternative way to do this is to use the attr data-bind binding instead of using a special binding handler to set the class in the element.

So, you still need to use the calculation to set the observable:

me.setClass = ko.computed(function() {
    return me.typeId() === 1 ? "mobile" : "business";
});

Then use the attr binding to set the class in the html element:

<td data-bind="attr: { class: setClass }, text: typeId"></td>
0
source

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


All Articles