Knockout JS - Use both static class name as well as data bound class name

前端 未结 3 1191
广开言路
广开言路 2021-02-05 23:17

Anyone know if I can have an html element with both a static class name as well as a dynamic, data-bound class name using KnockoutJS? Something like this:



        
3条回答
  •  旧巷少年郎
    2021-02-05 23:43

    I've seen a lot of different answers for this problem, mostly in combine dynamic and static classes through css binding, knockout.js which doesn't describe your problem, but offers solutions that could be applied here. Implementing ie. OOCSS principles is not easily done using Knockout, I've found.

    The only solution that appealed to me was to use a string concatenation

    
    

    You can use this in your example. In my opinion this is the least obtrusive, but it's ugly code and quickly becomes beyond readable.

    However, if you are able to use ECMAScript2015 in your project, you have the ability to use computed property names, which look like this.

    var name = "apple";
    var items = { [ "item-" + name ] : "juicy" }
    

    This means you can leave out the [].join(' ') functionality and add your classes the way Knockout actually prescribes it:

    
    
    var viewModel = {};
    
    viewModel.items = ko.observableArray([
      { 'name' : 'Apple' },
      { 'name' : 'Mango' },
      { 'name' : 'Raspberry' }
    ])
    
    ko.applyBindings(viewModel);
    .item {
      font-family: sans-serif
    }
    
    .item-Mango span {
      background-color: orange;
      color: #FFF;
    }
    
    
    

提交回复
热议问题