如何使用knockout js制作可观察的css类

时间:2013-11-09 21:43:07

标签: javascript jquery html css knockout.js

这是我的代码:

HTML:

<div>
   <input type="button" id="btnEnable" value="Enable" />
   <input type="button" id="btnDisable" value="Disable" />
</div>
<div id="myDiv">Some Text</div>
<textarea rows="5" id="someText" data-bind="enable: enableText"></textarea>

css:

.enabled{
  background-color: green;
}
.disabled{
  background-color: red;
}

的javascript:

$(document).ready(function () {
  $("#myDiv").addClass("enabled").html(" Enabled");

  $("#btnEnable").click(function () {
    $("#myDiv").removeClass("disabled");
    $("#myDiv").addClass("enabled").html(" Enabled");
  });
  $("#btnDisable").click(function () {
    $("#myDiv").addClass("disabled").html(" Disabled");
    $("#myDiv").removeClass("enabled");
  });
  var viewModel = function(){
    enableText =  ko.observable(true)
  }
  ko.applyBindings(viewModel);
});

当我单击禁用按钮时,将删除已启用的css类。此时,我需要通过KO observable viewModel禁用textarea。

var viewModel = function(){
    enableText =  ko.observable(here must return false when the enable css class is removed)
}

1 个答案:

答案 0 :(得分:2)

您需要点击,CSS和文本绑定:

$(document).ready(
    var viewModel= function () {
        var self = this;
        self.enableClick = function () {
            self.enable(true);
        };
        self.disableClick = function () {
            self.enable(false);
        };
        // Stores the enable state
        self.enable = ko.observable();
        // Get a text representation of the state 
        self.enableText = ko.computed(function(){
           return self.enable() ? 'Enabled' : 'Disabled';
        });
    };
    ko.applyBindings(new viewModel());
});

观点:

<div>
   <input type="button" data-bind="click: enableClick" value="Enable" />
   <input type="button" data-bind="click: disableClick" value="Disable" />
</div>

<div data-bind="text: enableText, css :{'enabled' : enable,'disabled' : enable() != true }">Some Text</div>
<textarea rows="5" id="someText" data-bind="enable: enable"></textarea>

See fiddle