当源为空/未定义KnockoutJS结合 [英] KnockoutJS binding when source is null/undefined

查看:132
本文介绍了当源为空/未定义KnockoutJS结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个较短/更清洁的方式去做空/未定义测试?

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>

而不是

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

我想

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

给予或采取()

或至少是一个简单的空操作符检查'? SelectedBusinessLine? []

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?

推荐答案

本页面提供了多种解决方案。相关的部分是这个:

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

对保护对象为空

如果你有一个可观察的,其中包含一个对象,你要绑定到对象的属性,那么你要小心,如果有机会的话,它可以为空或未定义。你可以写你的绑定,如:

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>

有许多方法来处理这​​一个。在preferred的方法是简单地使用模板绑定:

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>

通过这种方法,如果将selectedItem 为空,那么就不会呈现任何内容。所以,你不会看到未知的,你会在原来的绑定。然而,它确实有简化您的绑定额外的好处,因为现在你只需指定属性名称,而不是直接将selectedItem()。名称。这是最简单的解决方案。

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; });
  }
};

这是比原来的更好吗?我可能会说没有。它避免了JavaScript的在我们的约束力,但它仍然是pretty详细。

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>

您不会看到的未知值时,它是空的,但它至少在将selectedItem 为null不会导致错误。

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

我不认为preferred选择将要使用的模板,在这种情况下结合,特别是如果你有很多这些属性的绑定反对。

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.

这篇关于当源为空/未定义KnockoutJS结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆