我有一个画廊列表:
<div class="gallery">
<a href="#" class="next">next</a>
<a href="#" class="prev">prev</a>
<div class="frame">
<ul data-bind="foreach: designs">
<li>
<span class="text">№<span data-bind="text: getID()"></span> <span data-bind="text: getName()"></span></span>
<img src="images/img01.jpg" width="182" height="102" alt="image description"/>
</li>
</ul>
</div>
</div>
JS
Models.Design = function () {...}
function ViewModel(){
this.designs = ko.observableArray();
this.addDesign = function (_id, _name, _image, _video) {
var design = new Models.Design;
design.setID(_id);
design.setName(_name);
this.designs.push(design);
};
this.addDesign(1, "Image 1");
this.addDesign(2, "Image 1");
this.addDesign(3, "Image 1");
// at this moment there is no elements in DOM
}
问题:我需要写$('.gallery').galleryScroll();
来更新我的图库滑块吗?
答案 0 :(得分:3)
只需订阅观察者。对于集合的任何可见*更改,都将调用您的回调。
function ViewModel() {
this.designs = ko.observableArray();
this.designs.subscribe(function () {
$('.gallery').galleryScroll();
});
// ...
}
*可见意味着您对observable执行操作,而不是直接在底层数组上执行操作。
答案 1 :(得分:0)
我找到了解决方案:
ko.bindingHandlers.gallery = {
update: function(element, valueAccessor) {
setTimeout(function() {
$(element).parents('.gallery').galleryScroll();
});
}
};
<ul data-bind="foreach: designs, gallery:{}">
<li>....</li>
</ul>