KnockoutJS的select会以一种意想不到的方式影响可观察对象,这取决于select是什么时候创建的

KnockoutJS select affecting observable in an unexpected way depending on when the select is created

本文关键字:select 对象 观察 创建 什么时候 影响 取决于 意想不到 KnockoutJS 一种 方式      更新时间:2023-09-26

这是select:

       <div class="pull-left" data-bind="if: existingPackagingLevels().length > 0 && activateSelect() == true">
                <h4>Unique container</h4>
                <select data-bind="enable:  inUniqueContainerEditMode,
                                   options: containers,
                               optionsText: function(container){ return container.name() + ' ' + container.type() },
                              optionsValue: 'id',
                                     value: existingPackagingLevels()[0].uniqueContainerId,
                            optionsCaption: '--Select--'"></select>
              <button data-bind="visible: inUniqueContainerEditMode() == false, click: editUniqueContainer"><i class="icon-pencil"></i></button>
              <button data-bind="visible: inUniqueContainerEditMode, click: saveNewUniqueContainer">save</button>
              <button data-bind="visible: inUniqueContainerEditMode, click: cancelNewUniqueContainer">cancel</button>
            </div>

我用ajax加载existingPackagingLevels变量。数组中的第一个元素可能有也可能没有唯一的econtainerid。当existingPackagingLevels[0]. uniquecontainerid () != undefined时,我想显示选中的容器,否则显示"——Select——"选项。

问题:当我让select只在通过这个检查后创建时:

<div class="pull-left" data-bind="if: existingPackagingLevels().length > 0">

选择基本上覆盖了我现有的packaginglevels [0]. uniquecontainerid()并使其未定义。因此,我添加了另一个检查"activateSelect() == true",并在我放置延迟后开始显示为true。延迟100毫秒时,它的工作时间是一半一半。一半的时间它将覆盖该值并将其设置为未定义,一半的时间它将按预期工作并显示与uniqueContainerId对应的容器。如果有较大的延迟,它将一直工作。

那么我如何使它工作而不延迟与欺骗?

尝试valueAllowUnset参数

通常,当您在<select>元素上使用值绑定时,它意味着您想要关联的模型值来描述哪个项在<select>中被选中。但是如果你设置了模型值到列表中没有相应条目的东西?的默认行为是Knockout将您的模型值覆盖为因此,将其重置为已在下拉菜单中选择的任何内容防止模型和UI不同步。

然而,有时您可能不希望这种行为。如果相反你我想让Knockout允许你的模型可观察对象接受以下值在<select>中没有相应的条目,则指定valueAllowUnset: true。在这种情况下,当您的模型值不能在<select>,则在该位置没有选择值时间,它在视觉上是空白的。当用户稍后从下拉菜单中选择一个条目,这将写入您的和往常一样。