最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Knockout CSS styling, through a function as well as a binding - Stack Overflow

programmeradmin2浏览0评论

I know that you can use knockout to set the class as per a function return like so;

<span data-bind="css: styling()"></span>

You can also set them inline with a true/false value.

<span data-bind="css: {className: $parent.active() == $data}"></span>

Is there a way to do both in the one binding? My example is that I want to return a custom class depending on the type of the item displayed by the span element (there will be many of these) but I also want them to be highlighted if they are selected.

It seems that you cannot use functions on the right hand side of the object, and having two cause the second to overwrite the first.

Any ideas?

I know that you can use knockout to set the class as per a function return like so;

<span data-bind="css: styling()"></span>

You can also set them inline with a true/false value.

<span data-bind="css: {className: $parent.active() == $data}"></span>

Is there a way to do both in the one binding? My example is that I want to return a custom class depending on the type of the item displayed by the span element (there will be many of these) but I also want them to be highlighted if they are selected.

It seems that you cannot use functions on the right hand side of the object, and having two cause the second to overwrite the first.

Any ideas?

Share Improve this question asked Aug 20, 2013 at 8:59 ShadowShadow 9,4474 gold badges49 silver badges59 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

With this sample you will be able to specify the classes of each item.

View

<div data-bind="foreach: items" >
    <span data-bind="css : $parent.styling($data), text: $data"></span>
</div>

JS :

var vm = {
    items : ['a','b','c' ],

    styling : function(item ) {
        if(item =='a') return 'active';
        if(item =='b') return 'active bold';
        return '';
    }    
};

ko.applyBindings(vm);

See fiddle


Edit:

@Shadow : You right, if you pass a value to a puted it is to set (or write) it.

I think this would match your needs. When on an item the toggle function is called. Then the active observable will be changed and finally the styling puted.

JS

var Item =  function(data) {
    var self = this;
    self.name = data;
    self.active = ko.observable(false);
    self.styling = ko.puted(function(item ) {
        if(self.active()) return 'active';
        return '';  
    });
    self.toggle =  function(){
        self.active(!self.active());
    }
};

var vm = {
    items : [new Item('a'),new Item('b'), new Item('c') ]        
};


ko.applyBindings(vm);

View

<div data-bind="foreach: items" >
    <span data-bind="css : styling, text: name, click : toggle"></span>
    <br/>
</div>

See fiddle

发布评论

评论列表(0)

  1. 暂无评论