As part of my view I have:
<ul data-bind="foreach: caseStudies">
<li><a data-bind="text: title, attr: { href: caseStudyUrl }"></a></li>
</ul>
I want to run some 3rd Party code once knockout has updated the DOM.
caseStudies(data);
thirdPartyFuncToDoStuffToCaseStudyLinks(); <-- DOM not updated at this point.
Any idea on how I can hook into knockout to call this at the correct time?
Using the afterRender
binding can help you.
<ul data-bind="foreach: { data:caseStudies, afterRender:checkToRunThirdPartyFunction }">
<li><a data-bind="text: title, attr: { href: caseStudyUrl }"></a></li>
</ul>
function checkToRunThirdPartyFunction(element, caseStudy) {
if(caseStudies.indexOf(caseStudy) == caseStudies().length - 1){
thirdPartyFuncToDoStuffToCaseStudyLinks();
}
}
One accurate way is to use the fact that KnockoutJS applies bindings sequentially (as they are presented in html). You need define a virtual element after 'foreach-bound' element and define 'text' binding that calls your third party function.
Here is html:
<ul data-bind="foreach: items">
<li data-bind="text: text"></li>
</ul>
<!-- ko text: ThirdParyFunction () -->
<!-- /ko -->
Here is code:
$(function () {
var data = [{ id: 1, text: 'one' }, { id: 2, text: 'two' }, { id: 3, text: 'three' } ];
function ViewModel(data) {
var self = this;
this.items = ko.observableArray(data);
}
vm = new ViewModel(data);
ko.applyBindings(vm);
});
function ThirdParyFunction() {
console.log('third party function gets called');
console.log($('li').length);
}