2

我创建了一个自定义绑定到集成 owlcarousel。模板渲染完成后需要绑定轮播。我正在尝试使用 ko.applyBindingsToNode 来呈现模板绑定并在其上应用轮播,但它不起作用。在模板中传递给 foreach 的程序数组是一个 observableArray。它在应用模板绑定后增长。

绑定应用于具有属性的 UL 列表:

class="owl-carousel" data-bind="owlcarouselTemplate: { templateOptions: { name: 'grid-row-template', list: programs }, carouselOptions: { items : 5 } }"

自定义绑定如下:

ko.bindingHandlers.owlcarouselTemplate = {
init : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
/**/
    var value = ko.unwrap(valueAccessor());
    var tmplBinding = value.templateOptions;

    ko.applyBindingsToNode(element, { template: { name: tmplBinding.name, foreach: tmplBinding.list } }, bindingContext);


    /**/
},
update : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var value = ko.unwrap(valueAccessor());
    var tmplBinding = value.templateOptions;
    var owl = $(element).data('owlCarousel');

    valueAccessor = function() {
        return { name: tmplBinding.name, foreach: tmplBinding.list };
    }

    ko.bindingHandlers.template.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);

    if( owl ) {
        owl.destroy();
        owl.reinit();
    }
    else
        $(element).owlCarousel(value.carouselOptions);
}

}

4

0 回答 0