Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make conditional binding in knockout.js?

I tried this one :

<div data-bind="attr: {class: itemSelected? 'selected' : 'unselected' }"></div>

But it does not work :)

like image 655
Oguz Karadenizli Avatar asked Jul 22 '12 18:07

Oguz Karadenizli


1 Answers

Assuming you have this:

function viewModel() {
    this.itemSelected = ko.observable(true);
}
ko.applyBindings(new viewModel());​

Add a () after itemSelected to get the current value of the observable that you can use with the ternary operator:

<div data-bind="attr: { class: itemSelected() ? 'selected' : 'unselected' }"></div>​

http://jsfiddle.net/RK7Ty/


If you didn't need to assign the unselected class for the non selected state you could do this instead:

<div data-bind="css: { selected: itemSelected }"></div>​

http://jsfiddle.net/RK7Ty/1/

like image 112
kendaleiv Avatar answered Sep 19 '22 11:09

kendaleiv