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?
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With