Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

knockout.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...