【发布时间】:2015-08-16 13:48:55
【问题描述】:
我遇到的问题与 AJAX 的动态选择选项有关。
用例是更改选择 #1 中的值应该通过 ajax 填充选择 #2 中的选项。不常见的是 select #2 的值也是异步来的,但是使用不同的 ajax。
jsFiffle 显示以下代码(简化 - 只有 1 个类似 ajax 的超时)。我们有 2 个选择,一个带有静态选项,另一个带有动态选项。两者都有值绑定。
<select id="select_1" data-bind="value: select_1_value">
<option selected>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="select_2" data-bind="options:selectOptions, value: select_2_value"></select>
Select 2 value is <span data-bind="text: select_2_value">
js部分长这样:
var vm = function AppViewModel() {
this.selectOptions = ko.observableArray(['a','b','c']);
this.select_1_value = ko.observable(1);
this.select_2_value = ko.observable('a');
this.computedValue = ko.computed( function () {
<!-- prevent from initial -->
if (this.select_1_value() != 1)
{
console.log('changed');
this.select_1_value();
this.selectOptions.removeAll()
var self = this
setTimeout(function(){
self.selectOptions.push(['e']);
self.selectOptions.push(['f']);
<!-- DOES WORK But i do not want it here -->
<!--self.select_2_value('f'); -->
}, 1000);
<!-- DOES NOT WORK -->
this.select_2_value('f');
}
}, this);
}
$(function() {
ko.applyBindings(new vm());
});
您在 jsfiddle 中可以看到,当 select_2_value 未设置在异步部分时,它会在清除选项 observableArray 时被覆盖。
我认为存在设计缺陷。你能帮我指出来吗?谢谢!
【问题讨论】:
标签: javascript ajax knockout.js knockout-3.0