KnockoutJS binding when source is null/undefined

2019-01-31 06:48发布

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?

6条回答
2楼-- · 2019-01-31 06:50

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!

查看更多
贪生不怕死
3楼-- · 2019-01-31 06:53

Most of the above solutions didn't work for me quite out of the box, since I only wanted to apply this to a single element in a foreach so I modified the accepted answer's approach a bit:

<span data-bind="text: ((typeof info).localeCompare('undefined')) ? info : ''"></span>
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-31 07:04

Most of these solutions do not work in a certain case for me, where I am setting an attribute:

<div role="combobox" data-bind="attr: {
  'aria-activedescendant': activedescendant() ? activedescendant().id : null
}">
  ...
</div>

The template and with bindings would not work here, because if I did not have an active descendant, then my div would be empty. For my solution, I created an observable method:

ko.observable.fn.get = function (propertyName, defaultValue) {
    var
    self = this(),
    propertyValue;

    if (self != null) {
        propertyValue = ko.unwrap(self[propertyName]);
    }

    return propertyValue || defaultValue;
}

Which allows me to change my binding to this:

<div role="combobox" data-bind="attr: {
  'aria-activedescendant': activedescendant.get('id')}">
  ...
</div>
查看更多
放荡不羁爱自由
5楼-- · 2019-01-31 07:06

One way not mentioned in the otherwise 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.

查看更多
看我几分像从前
6楼-- · 2019-01-31 07:10

I prefer this method

Create a custom binding

ko.bindingHandlers.safeText = {
    update: function (element, valueAccessor, allBindingsAccessor) {
        try {
            var tryGetValue = valueAccessor()();
            ko.bindingHandlers.text.update(element, valueAccessor());
        } catch (e) {
            ko.bindingHandlers.text.update(element, function () { return ""; });
        }
    }
};

Usage

data-bind="safeText: function() { return my().nested.object.property; }

The only extra stuff you need to add is to wrap your original value with 'function() { return ... }'

This however, will stop all errors beneath the value call. You could improve the custom binding by only looking for 'undefined' exceptions. You may also like to improve this binding by adding in a default text option.

查看更多
beautiful°
7楼-- · 2019-01-31 07:12

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.

查看更多
登录 后发表回答