Knockout JS css "else" conditons

I would like to do it 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 prevents the creation of a warning icon class. I tried several access options in the data binding attribute, for example firstPlace == false and (!firstPlace) . Instead, I need 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 it works. And cheers for JS knockout, which is really very interesting to use. But that just seems wrong. Does anyone have a better method?

+4
source share
2 answers

When you use logical operations in a data binding attribute, you must put () after the observed or calculated names.

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

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> 
+4
source

Source: https://habr.com/ru/post/1436808/


All Articles