淘汰赛,css绑定动态和条件

时间:2016-06-01 13:33:26

标签: javascript knockout.js knockout-2.0

我不想通过css绑定添加条件css类和动态css类。

像这样:

data-bind="css: {$data.something() : true, open : showOpen()  }"

2 个答案:

答案 0 :(得分:1)

最清楚的可能是将它们组合在一个计算中:

function ViewModel() {
  var self = this;
  
  self.something = ko.observable("danger");
  self.showOpen = ko.observable(true);
  
  self.cssClass = ko.computed(function() {
    return self.something() + (self.showOpen() ? " open" : "");
  });
}

ko.applyBindings(new ViewModel());
div { padding: 10px; }
.danger { background-color: orange; }
.open { border: 5px solid gray; border-width: 5px 5px 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>

<div data-bind="css: cssClass"> my div with class: <code data-bind="text: cssClass"></code> </div>
<hr>
<label><input type="checkbox" data-bind="checked: showOpen"> showOpen</label>
<br>
<input type="text" data-bind="value: something, valueUpdate: 'afterkeydown'">

允许您对整个事物进行单元测试,并使您的视图保持简洁。

答案 1 :(得分:0)

我更喜欢这样的自定义绑定:

ko.bindingHandlers.klass = {
  init: function (el, val) {
    var prevClass = null
   
    ko.computed(function () {
      if (prevClass)
        $(el).removeClass(prevClass);
      
      var newClass = ko.unwrap(val());
      
      $(el).addClass(newClass);
      prevClass = newClass;
    }, null, {disposeWhenNodeIsRemoved: el})
    
  }
}

var vmo = {
  cssClass: ko.observable('a'),
  toggle: function () { vmo.cssClass(vmo.cssClass() == 'a' ? 'b' : 'a') }
}

ko.applyBindings(vmo);
.a {
  color: red;
}
.b {
  color: blue;
}
.another {
  text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<p data-bind='klass: cssClass, css: {another: true}'>Hello</p>
<button data-bind='click: toggle'>Toggle</button>