2014-03-05 23 views
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/

回答

12

兩個例子這是默認bahavior:淘汰賽強制值以匹配現有的選項,如果有將取消設置的觀察到沒有existings選項。

但是在KO 3.1中有新的設置。這被稱爲valueAllowUnset它正在處理這種情況。

Knockout.js 3.1 Released

  • 使用此選項設置爲true,淘汰賽不會強制值以匹配現有的選項。
  • 在不匹配的情況下,選擇將被設置爲空選項,但該值不會被覆蓋。
  • 這對於延遲加載選項並存在現有值的場景非常有用。

因此,如果您升級到3.1 Knockout.js你可以寫

<select data-bind="options:  (function(){return $root.select2.rows;})(), 
        optionsText: function(item){return item.name;}, 
        optionsValue: function(item){return item.id;}, 
        value: selectedThing2, 
        valueAllowUnset: true, 
        optionsCaption: 'Choose...'"> 

演示JSFIddle

+0

做得好,對淘汰賽的人們做得很好,他們解決了我的問題,在我昨天和現在閱讀手冊之間有一段時間。 –

相關問題