How to run code after Knockout JS has updated the DOM

后端 未结 2 639
长发绾君心
长发绾君心 2021-01-07 16:32

As part of my view I have:

相关标签:
2条回答
  • 2021-01-07 17:11

    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();
        }
    }
    
    0 讨论(0)
  • 2021-01-07 17:17

    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);
        }
    
    0 讨论(0)
提交回复
热议问题