pedalpete
pedalpete

Reputation: 21546

Knockout bindings not updating class styles

I'm trying to figure out how to add and remove classes from html with knockout.

What should happen is that when I click truck, the button should update to be of class btn-red, and the car button should have it's btn-red removed.

I can see that the event binding is working because the alerts are triggered and the correct value is returned, but I can't get the view to update.

I've put together a really simple JSFiddle.net/N8GBB/11/ (stackoverflow won't let me post the link for some reason) Here's the code I'm using in jsfiddle

<button class="btn" data-bind="css:{'btn-red':type()=='car'}, click: set_to_car">Car</button>
<button class="btn" data-bind="css:{'btn-red':type()=='truck'}, click: set_to_truck">Truck</button>
var vehicle={ 
    type:ko.observable("car"),
           set_to_car : function(){
        this.type='car'
        alert(this.type);
    },
        set_to_truck: function(){
            this.type='truck'
     alert(vehicle.type);        
    }};

ko.applyBindings(vehicle);

Upvotes: 0

Views: 691

Answers (1)

nemesv
nemesv

Reputation: 139768

You are not setting your type observable correctly.

The ko.observable method returns a function so if you want to change its value you need to call it as a function with the new value as the argument.

var vehicle={ 
    type:ko.observable("car"),
           set_to_car : function(){
        this.type('car');
    },
        set_to_truck: function(){
            this.type('truck');  
    }};

Demo JSFiddle.

You can read more about Reading and writing observables in the documentation.

Upvotes: 1

Related Questions