KnockoutJS binding when source is null/undefined

Is there a shorter/cleaner way to do the null/undefined testing?

<select data-bind="options: SelectedBusinessLine() ? SelectedBusinessLine().Clusters() : [],
                               optionsText: 'Title',
                               value: SelectedCluster,
                               optionsCaption: 'Select Cluster..'">
            </select>

Instead of

data-bind="options: SelectedBusinessLine() ? SelectedBusinessLine().Clusters() : [],

i would like

data-bind="options: SelectedBusinessLine().Clusters(),

give or take the ()

Or at least a simpler null operator check '??' SelectedBusinessLine ?? []

Or a binding param to auto check for null or silent fail.

Any ideas if this is possible?


Solution 1:

This page provides several solutions. The relevant part is this one:

Protecting against null objects

If you have an observable that contains an object and you want to bind to properties of that object, then you need to be careful if there is a chance that it can be null or undefined. You may write your binding like:

<span data-bind="text: selectedItem() ? selectedItem().name() : 'unknown'"></span>

There are a number of ways to handle this one. The preferred way would be to simply use the template binding:

var viewModel = {
  items: ko.observableArray(),
  selectedItem: ko.observable()
};

<ul data-bind="template: { name: 'editorTmpl', data: selectedItem }"></ul>
<script id="editorTmpl" type="text/html">
  <li>
    <input data-bind="value: name" />
  </li>
</script>

With this method, if selectedItem is null, then it just won’t render anything. So, you would not see unknown as you would have in the original binding. However, it does have the added benefit of simplifying your bindings, as you can now just specify your property names directly rather than selectedItem().name. This is the easiest solution.

Just for the sake of exploring some options, here are a few alternatives:

You could use a computed observable, as we did before.

viewModel.selectedItemName = ko.computed(function() {
  var selected = this.selected();
  return selected ? selected.name() : 'unknown';
}, viewModel);

However, this again adds some bloat to our view model that we may not want and we might have to repeat this for many properties.

You could use a custom binding like:

<div data-bind="safeText: { value: selectedItem, property: 'name', default: 'unknown' }"></div>

ko.bindingHandlers.safeText = {
  update: function(element, valueAccessor, allBindingsAccessor) {
    var options = ko.utils.unwrapObservable(valueAccessor()),
    value = ko.utils.unwrapObservable(options.value),
    property = ko.utils.unwrapObservable(options.property),
    fallback = ko.utils.unwrapObservable(options.default) || "",
    text;

    text = value ? (options.property ? value[property] : value) : fallback;

    ko.bindingHandlers.text.update(element, function() { return text; });
  }
};

Is this better than the original? I would say probably not. It does avoid the JavaScript in our binding, but it is still pretty verbose.

One other option would be to create an augmented observable that provides a safe way to access properties while still allowing the actual value to be null. Could look like:

ko.safeObservable = function(initialValue) {
  var result = ko.observable(initialValue);
  result.safe = ko.dependentObservable(function() {
    return result() || {};
  });

  return result;
};

So, this is just an observable that also exposes a computed observable named safe that will always return an empty object, but the actual observable can continue to store null.

Now, you could bind to it like:

<div data-bind="text: selectedItem.safe().name"></div>

You would not see the unknown value when it is null, but it at least would not cause an error when selectedItem is null.

I do think that the preferred option would be using the template binding in this case, especially if you have many of these properties to bind against.

Solution 2:

One way not mentioned in the excellent page referenced by another answer is to use with

<div data-bind="with: selecteditem">
    <form>
        <fieldset>
            <div>
                <label>first name</label>
                <input data-bind="value: firstname"></input>
            </div>
            <div>
                <label>lasst name</label>
                <input data-bind="value: lastname"></input>
            </div>
        </fieldset>
        <div>
            <a href="#" data-bind="click: $root.savechanges">Save</a>
        </div>
    </form>
</div>

This whole UI will disappear if selecteditem is null.

Solution 3:

The "With" works (probably the others works too...)

But with the "With" the role UI disappear/appear even if there are conditions inside... For Example... I need to set a Status (true/false) button, but only if the Status isn't null...

<!-- ko ifnot: Status() == null -->
<span data-bind="if: Status">
    <a class="rk-button rk-red-action" data-bind="click: changeStatus"><i class="rk-ico rk-ico-save"></i>Desativar</a>
</span>
<span data-bind="ifnot: Status">
    <a class="rk-button rk-black-action" data-bind="click: changeStatus"><i class="rk-ico rk-ico-save"></i>Ativar</a>
</span>
<!-- /ko -->

This works. In this case.

But sometimes just the "With" works like Simon_Weaver said!