简体   繁体   中英

How to run code after Knockout JS has updated the DOM

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM