1

I'm using the following knockout code to display properties from an object. Using the with i can check if the properties in this object exist.

<!-- ko with: Bunk1 -->
<div data-bind="css: Color">
    <div class="row no-margin">
        <div>
            <div data-bind="text: Name"></div>
            <div data-bind="text: FirstName"></div>
        </div>
    </div>
</div>
<!-- /ko -->

This is the model:

var viewModel = function () {
    var self = this;
    self.Bunk1 = ko.observable();
    self.Bunk2 = ko.observable();
    ...

    ...

    // 'val' is loaded with $.ajax 
    // this code might not be executed and  Bunk1 can fail to initialize.
    var model = new BunkModel();
        model.initModel(val);
        self.Bunk1(model);

    ...
}

function BunkModel() {
    var self = this;
    self.Color = ko.observable();
    self.Name= ko.observable();
    self.FirstName= ko.observable();

    self.initModel = function (values) {
        self.Color(self.mapColor(values.color));
        self.Name(values.name);
        self.FirstName(values.firstName);
    }
}

What i would like to do is to display an alternative div if there is no data, something like an else to the ko with. How can i bind the object properties but display alternative data if they don't exist.

Thomas Schneiter
  • 1,103
  • 2
  • 19
  • 35
  • What about a simple `ko if: Bunk1() === undefined` or `ko if: Bunk1() === null` after the `ko with` block? – user247702 Sep 22 '16 at 09:38
  • didn't know about `undefined`. `ko if Bunk1() === undefined` seems to work. `null` doesn't work because it seems to be initialized after `self.Bunk1 = ko.observable();` – Thomas Schneiter Sep 22 '16 at 09:49
  • OK, I'll convert that to an answer. Asked first because it seemed rather obvious, but perhaps not to a Knockout beginner :) – user247702 Sep 22 '16 at 09:50

2 Answers2

1

When creating a new observable without passing a value, its value will be undefined. This means you can simply add a conditional block below the existing with block:

<!-- ko if: Bunk1() === undefined -->
content here
<!-- /ko -->

Note that you need to use parentheses when doing a comparison like this, Bunk1 === undefined would check if the observable itself is undefined instead of its underlying value.

user247702
  • 23,641
  • 15
  • 110
  • 157
1

In addition to @Stijn answer.

You can use "ifnot" binding:

<!-- ko ifnot: Bunk1 -->
content here
<!-- /ko -->
TSV
  • 7,538
  • 1
  • 29
  • 37
  • 1
    This'll work too, indeed, since `undefined` is [falsey](http://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript). – user247702 Sep 22 '16 at 10:01