2011-11-01 25 views
1

我正試圖在照片庫中結合knockout.js和colorbox。如何更新colorbox中的底層數據?

我有一個觀察的陣列中的所有照片,並且代碼看起來是這樣的:

<script type='text/javascript> 
     function Photo(src, comment) { 
      this.image = src; 
      this.comment = ko.observable(comment); 
     } 

     var view_model = { 
      photos: ko.observableArray([ 
       new Photo('/gallery/img1.jpg', 'Some comment'), 
       new Photo('/gallery/img2.jpg', 'Some other comment'), 
       new Photo('/gallery/img3.jpg', '') 
      ]), 
      current_photo: ko.observable() 
     }; 

     $(document).ready(function(){ 
      $('ul#gallery').colorbox({href: '#photo-detail'}); 
     }); 
    </script> 

    <script id='photoTemplate' type='text/html'> 
     <li> 
      <img src='{{src}}' /> 
      <div>{{comment}}</div> 
     </li> 
    </script> 

    <body> 
     <ul id='gallery' data-bind='template: "photoTemplate, foreach:photos"'</ul> 

     <div style='display: none'> 
      <div id='photo-detail'> 
       <img data-bind='attr: { src: current_photo().src }'/> 
       <input type="text" data-bind='value: current_photo().comment'/> 
      </div> 
     </div> 
    </body> 

我在事件處理程序顏色框,一個新的圖像加載時更新CURRENT_PHOTO。一切工作,直到我編輯評論。

看起來knockout刪除了DOM元素,並用新的替換它,所以當移動到下一張照片,然後再回來時,colorbox會出錯。如果我關閉colorbox並重新初始化,它會再次運行。

有沒有辦法更新colorbox的數據,而不關閉它?

回答

2

我想,而不是使用jQuery模板,只需使用淘汰賽1.3和新的foreach綁定:

http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/

<ul data-bind="foreach: products"> 
    <li> 
     <strong data-bind="text: name"></strong> 
     <em data-bind="if: manufacturer"> 
      &mdash; made by <span data-bind="text: manufacturer.company"></span> 
     </em> 
    </li> 
</ul> 

它基本上只是複製父下的節點,所以你不除非它更復雜,否則需要使用模板。

你是正確的,你正在使用的jquery模板實現重新創建可能會殺死colorbox的節點,我認爲新的foreach實現應該離開節點並且工作得更好。

如果失敗,但您可能必須編寫自己的自定義挖空綁定或將列表綁定到colorbox。

+1

新的foreach綁定非常完美!謝謝! – Simon

相關問題