[SalesForce] Initializing Javascript plugin after loading data in lightning component

I am displaying a list of cases in a table and want to use DataTables jQuery plugin to implement sorting, pagination, search on the table. The list of cases is retrieved as part of component initialization. The part that am struggling is how do I know that the aura:iteration is complete on the table so that I can invoke the initialization code of DataTables plugin?

CaseList.cmp

<aura:component controller="CaseController">
 <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

 <table id="myTable">
     <thead><tr><th>ID</th></tr></thead>
     <tbody>
       <aura:iteration items="{!v.cases}" var="case">
         <tr><td>{!case.Id}</td></tr>
       </aura:iteration>
     </tbody>
</table>
</aura:component>

CaseList.controller

({ doInit : function(cmp, evt, hlp){ hlp.getCaseList(component); } })

CaseList.helper

({
   getCaseList: function(component) {
       var action = component.get("c.getCases");
       action.setCallback(this, function(actionResult) {
           component.set("v.cases", actionResult.getReturnValue());  
       });
       $A.enqueueAction(action);
   }   
})

CaseController.cls

public class CaseController 
{
   @AuraEnabled
   public static List<Case> getCases() {
       return [SELECT Id FROM Case ORDER BY CreatedDate ASC limit 10];
   }   
}

I need to call "$('#myTable').DataTable()" after the table displays list of cases. I would think that after I set "v.cases" in CaseList.helper, I should be able to write the DataTable initialization code. While there were no javascript errors, the plugin was not able to work on the data that was dynamically added as part of the aura iteration. Hence I was thinking that the right place to add the initialization would be after aura:iteration has completed its work. Something on the lines of oncomplete of apex:repeat. Any thoughts?

Best Answer

If you just want the plugin to initialize after scripts has been loaded ,take a look at ltng require

This has afterScriptsloaded attribute to call your JS function

<ltng:require scripts="/resource/jsLibOne,/resource/jsLibTwo" 
    styles="/resource/cssOne,/resource/cssTwo"
    afterScriptsLoaded="{!c.afterScriptsLoaded}"/>

Its worth checking the lifecycle of the component Rendering

enter image description here

Related Topic