I am trying to combine knockout.js and colorbox in a photo-gallery.
I have all photos in an observable array, and the code looks something like this:
<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>
I update current_photo in the event-handler for colorbox, when a new image loaded. Everything works until i edit a comment.
It seems like knockout removes the DOM-element, and replaces it with a new, so when moving to next photo and then back again, colorbox bugs out. If i close colorbox and reinitialize, it works again.
Is there a way to update the the data for colorbox, without closing it?
I think instead of using the jquery template, just use Knockout 1.3 and the new foreach binding:
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">
— made by <span data-bind="text: manufacturer.company"></span>
</em>
</li>
</ul>
It basically just duplicates the nodes underneath the parent, so you don't need to use the templating unless its much more complicated.
You are correct that the jquery template implementation you are using recreates the nodes which probably kills the colorbox, I think the new foreach implementation should leave the nodes in place and work better.
If that fails though you may have to write your own custom knockout binding or something to bind a list to colorbox.