【发布时间】:2014-04-07 14:01:17
【问题描述】:
我正在使用敲除创建一个选择元素,选项必须设置较晚(选项是通过从服务器加载它们来设置的)。这导致初始值丢失。下面我有一些工作代码,它可以满足我的要求,但是从服务器加载替换为静态表。
如果setupSelect(); 行移动到脚本的末尾(这模拟了对服务器的异步ajax 调用),那么选择会要求我选择。
我认为当没有选择时,值被覆盖,然后选择到达,但该值现在为空。
看起来我知道问题出在哪里,但不知道如何解决。
你能告诉我如何让它工作吗?
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
</head>
<body>
<p>
Your thing:
<select data-bind="options: (function(){return $root.select1.rows;})(),
optionsText: function(item){return item.name;},
optionsValue: function(item){return item.id;},
value: selectedThing1,
optionsCaption: 'Choose...'">
</select>
<span data-bind="visible: selectedThing1">
You have chosen a thing with id
<span data-bind="text: selectedThing1() ?
selectedThing1() :
'unknown'">
</span>.
</span>
</p>
<script type="text/javascript">
var viewModel = {
select: {rows: ko.observableArray() },
selectedThing : ko.observable() // Nothing selected by default
};
function setupSelect(){
//in the real application rows_raw is populated from a server using $.ajax
var rows_raw= [
{name: "a thing", id:1},
{name: "one more thing", id:2},
{name: "another thing", id:3}
];
$.each(rows_raw, function(index, item){
viewModel.select.rows.push(item);
});
}
//setupSelect(); //when loading from server (using $.ajax in async mode), then this line is effectivly moved to the end of the script.
viewModel.selectedThing(2); //set ititial value
ko.applyBindings(viewModel);
setupSelect(); //when loading from server (using $.ajax in async mode), then this line is effectivly moved to the end of the script.
</script>
</body>
</html>
你也可以在这里看到这两个例子http://jsfiddle.net/V33NT/1/
【问题讨论】: