knockout set css conditionally

2019-06-08 02:04发布

Sorry for maybe uncorrect question, but I feel really confused. I need to set the css class of an item in a foreach loop based on the value of an item's property.

self.CssBind = ko.computed(function (task) {
    var CssBind = '';
    if (getComplexity(task) === 'Easy') {
     CssBind = "green";
 } else if (getComplexity(task) === 'Intermediate') {
     CssBind = 'yellow';}
 else if (getComplexity(task) === 'Difficult') {
     CssBind = 'red';
 }
 return CssBind;
});

I tried to get complexity in such way but have undefined.... (in controller there is method that accepts task and returns complexity)

self.complexity = ko.observable();
function getComplexity (task) {
    ajaxHelper(taskItem, 'GET').done(function (data) { self.complexity(data); });
};

In html

<div class="panel panel-default" data-bind="foreach:{data:tasks, as: 'task'}">
        <div class="panel-heading">
          <a data-toggle="collapse" data-parent="#accordion" data-bind="text: Name, attr: { href : '#collapse' + task.Id}, css: {color: CssBind}">
          </a>
        </div>
        <div data-bind="attr: { id : 'collapse' + task.Id}" class="panel-collapse collapse">
            <div class="panel-body">
                <span data-bind="text: Name"></span>
            </div>
        </div>
    </div>

What to change to make it work?

1条回答
一纸荒年 Trace。
2楼-- · 2019-06-08 02:42

Your computed is probably defined on the root view-model and when you're calling it you're already in a foreach: tasks scope. You need to use the $root keyword to point to CssBind.

Also, no need for a computed, regular function will do easier (especially with argument passing):

self.CssBind = function (task) {
    var CssBind = '';
    if (ko.unwrap(task.getComplexity) === 'Easy') {
     CssBind = "green";
 } else if (self.getComplexity() === 'Intermediate') {
     CssBind = 'yellow';}
 else if (self.getComplexity() === 'Difficult') {
     CssBind = 'red';
 }

 return CssBind;
});

And in your HTML:

<a data-toggle="collapse"
   data-parent="#accordion"
   data-bind="text: Name, attr: { href : '#collapse' + task.Id}, style: {color: $root.CssBind.bind(null, task)}">

Please notice that I change the binding handler from css to style (the former is used to apply CSS classes while the latter applies explicit CSS rules).

查看更多
登录 后发表回答