我正在尝试将 knockout.js 和 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>
当加载新图像时,我在 colorbox 的事件处理程序中更新 current_photo。在我编辑评论之前一切正常。
看起来 knockout 删除了 DOM 元素,并用一个新元素替换它,所以当移动到下一张照片然后再返回时,颜色框出现错误。如果我关闭 colorbox 并重新初始化,它会再次工作。
有没有办法在不关闭的情况下更新颜色框的数据?
最佳答案
我认为与其使用 jquery 模板,不如使用 Knockout 1.3 和新的 foreach 绑定(bind):
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>
它基本上只是复制父节点下的节点,因此您不需要使用模板,除非它更复杂。
您是正确的,您正在使用的 jquery 模板实现重新创建了可能会破坏颜色框的节点,我认为新的 foreach 实现应该保留节点并更好地工作。
如果失败,尽管您可能必须编写自己的自定义挖空绑定(bind)或将列表绑定(bind)到 colorbox 的东西。
关于javascript - 如何更新 colorbox 中的基础数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965430/