0

I have this data-bind="style: { 'background-color': storedColor }"

but stored color can be null in the database so i wanted to add a default color of blue incase it is null so it doesn't look like it is broken or something wrong

072et
  • 345
  • 2
  • 8
  • 21

2 Answers2

2

You can use the || operator to combine the return from your observable with your desired default value:

data-bind="style: { 'background-color': storedColor() || 'blue' }"

If storedColor() is null, the || operator will instead return 'blue' instead.

Community
  • 1
  • 1
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
0

Let me suggest that it's a good idea to use your view model to more closely model what you want in the view. Instead of putting defaulting logic into your HTML, put it into your viewmodel, either by changing the value of storedColor or by having a separate computed that takes care of defaulting.

Taking it one step further, instead of specifying the object literal for your style binding parameter, you can use a simple function (or, equivalently, a computed observable) there, and all your logic for how that style is applied is handled in your code. Your HTML markup stays simple regardless of how much stying there is to do.

vm = {
  colors: ['red', 'green', 'yellow', 'blue'],
  sizes: ['25', '35', '45', '50'],
  selectedColor: ko.observable(),
  selectedSize: ko.observable('25'),
  myStyle: function() {
    var mySize = vm.selectedSize() + 'pt',
      myColor = vm.selectedColor() || 'blue';
    return {
      height: mySize,
      width: mySize,
      'background-color': myColor
    };
  }

};

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<div data-bind="style: myStyle()"></div>
<select data-bind="options:colors, optionsCaption:'(color)', value: selectedColor"></select>
<select data-bind="options:sizes, value: selectedSize"></select>
Roy J
  • 42,522
  • 10
  • 78
  • 102