Pregunta

I'm trying out Knockout for the first time and have gone through the basic tutorial and looked at various examples.

But trying it myself (jsFiddle) does not quite work.

All I want to do, is to add the class open to a div when clicking a "Click me" text.

What am I missing here?

//HTML
<div class="clickMe" data-bind="click: expand">Click me</div>

<div class="wrapper">        
    <div class="content" data-bind="css: {expandMenu : open}">
      This is a test
    </div>
</div>

//JS
function viewModel() {
    var self = this;

    self.expandMenu = ko.observable(false);

    self.expand = function () {
        self.expandMenu(!self.expandMenu());
    };
};
ko.applyBindings(new viewModel());

// CSS
.content {display: none;}
.content.open {display: block;}    
¿Fue útil?

Solución

To fix this switch class name with observable in css binding:

data-bind="css: {open : expandMenu}"

Also, you can use css binding is such formats:

data-bind="css: getClassForSomething()" // getClassForSomething must return css class (string)

and

data-bind="css: { open: isSomethingDone() }" // considering that isSomethingDone is viewmodel's method
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top