I'm using jquery accordion in a KO bindingHandler, I have to populate the DOM, used by accordion UI, using ajax by an app requirement.
this.faqList = ko.observableArray();
$.ajax({
url: 'getFaqs'
}).done(function( data ) {
that.faqList(data);
});
My bindingHandler should be as simple as
ko.bindingHandlers.koAccordion = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).accordion(valueAccessor());
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).accordion(valueAccessor());
}
};
The update method is called when the observableArray (faqList) changes, but at that moment UI accordion needs the DOM structure already populated which is not true, seems KO creates after the update method is called. How could I achieve call update after the DOM structure is populated with the new contents?
Here's the default DOM.
<ul class="question-list" data-bind="koAccordion: {
active: false,
autoHeight: false,
collapsible: true}">
<!-- ko foreach: faqList -->
<li>
<div class="header">
<span class="rigth-arrow"></span>
<a href="#" data-bind="text: title"></a>
</div>
<div class="content">
<h2 data-bind="text: title"></h2>
<div data-bind="text: content"></div>
</div>
</li>
<!-- /ko -->
</ul>
koAccordion.updateis useless because you never update that binding value: it's static in the markup and contains no observables.foreachbinding providesafterRendercallback for your purposes:However, in this case you have to move accordion options out of binding values. If you insist on having custom binding one way to do this is to delegate work to
foreachbinding, insertingafterRenderinto binding values on the way:Using it like this:
See demo page I forked from the one in the post: http://codepen.io/anon/pen/IJpuj