5
我正在使用knockout來創建select元素,選項必須設置得晚(選項是通過從服務器加載它們來設置的)。這會導致初始值丟失。下面我有一些工作代碼它做我想要的,但用服務器加載替換爲靜態表。Knockout選擇綁定,當選項延遲添加時不記住值
如果行setupSelect();
被移動到腳本的末尾(這模擬到服務器的異步ajax調用),那麼select會要求我選擇。
我認爲,當沒有選擇的價值被覆蓋,然後選擇到達,但價值現在爲空。
它看起來像我知道問題是什麼,但不知道如何讓它工作。
你能告訴我如何讓它工作嗎?
<!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/
做得好,對淘汰賽的人們做得很好,他們解決了我的問題,在我昨天和現在閱讀手冊之間有一段時間。 –