在手动将选项添加到绑定选择元素的场景中,可观察对象的原始值在 applyBindings 之后丢失。如果使用选项绑定添加选项,则该值不会丢失。我在这里演示了效果:http: //jsfiddle.net/nigelw/CkyjC
编辑: 请注意,我正在谈论选择的初始创建/绑定 - 而不是稍后将选项添加到现有选择。
是否有一个原因?
示例代码:
<!-- In this test, select options are added manually within a
foreach construct. Select works as expected, but initial
value of observable is cleared. -->
<select data-bind="value: ChoiceA">
<!-- ko foreach: Choices -->
<option data-bind="text: Name, value: Id"></option>
<!-- /ko -->
</select>
<p>ChoiceA = [<span data-bind="text: ChoiceA"></span>]</p>
<!-- In this test, select options are added using options binding.
Select works as expected and initial value of observable is kept. -->
<select data-bind="options: Choices, optionsText: 'Name', optionsValue: 'Id', value: ChoiceB"></select>
<p>ChoiceB = [<span data-bind="text: ChoiceB"></span>]</p>
<script type="text/javascript">
var model = {
// Store the selection here. Initialised to 3. This selects
// the correct option, but the value then disappears until a
// new selection is made.
"ChoiceA": ko.observable(3),
// Store the selection here. Initialised to 3. This selects
// the correct option, and the value stays as expected.
"ChoiceB": ko.observable(3),
// The options
"Choices": ko.observableArray([
{ Id: 1, Name: "Option1" },
{ Id: 2, Name: "Option2" },
{ Id: 3, Name: "Option3" }])
};
ko.applyBindings(model);
</script>