Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS css "else" conditons

Tags:

knockout.js

I would like to do this in Knockout.

    <span class="badge" data-bind="text: rank, css: {'badge-success': firstPlace, 
        'badge-warning': !firstPlace}"></span>

Where my javascript model class has this method

    self.firstPlace = ko.computed(function() {
        return self.rank() == 1;
    });

This fails to produce the 'badge-warning' class. I tried a few invocation variations in the data-bind attribute such as firstPlace == false and (!firstPlace). Instead I have to add a second inverse method to my model:

    <span class="badge" data-bind="text: rank, css: {'badge-success': firstPlace, 
        'badge-warning': notFirstPlace}"></span>


    // YUCK
    self.notFirstPlace = ko.computed(function() {
        return self.rank() != 1;
    });

Of course, this works. And hooray for Knockout JS which really is a lot of fun to use. But this just seems wrong. Anybody have a better method?

like image 212
carbontax Avatar asked Sep 28 '12 12:09

carbontax


People also ask

What is ko observable?

An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.

What is Knockout computed?

Master KnockoutJS : Knockout JS - JavaScript MVVM Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.


2 Answers

When you are using logical operations in data-bind attribute you should put () after observable or computed names.

<span class="badge" data-bind="text: rank, css: {'badge-success': firstPlace, 
    'badge-warning': !firstPlace()}"></span>
like image 107
Artem Vyshniakov Avatar answered Sep 30 '22 14:09

Artem Vyshniakov


If you want to evaluate firstPlace() only once, you can write the css binding as an inline function:

<span class="badge" data-bind="text: rank, css: (firstPlace() ? 'badge-success' : 'badge-warning')"></span>
like image 34
Cᴏʀʏ Avatar answered Sep 30 '22 12:09

Cᴏʀʏ