1

How could I make a JavaScript class from a different file accessible in the arbitrary lightning controller?

I found this question from SO, but it does not help me.

So, the best way I was able to come up with is to create a class in helper or .js static resource and then return it when needed to the controller. Are there better approaches you may know about?

4

You can load JavaScript libraries (whether your own or a third party's) as Static Resources. They're then available to your Lightning component controllers by using the <ltng:require> component. Here's an example from one of my projects that uses Leaflet mapping:

Component XML Markup

<ltng:require styles="{!$Resource.Leaflet + '/leaflet.css'}" 
              scripts="{! $Resource.Leaflet + '/leaflet-src.js'}"
              afterScriptsLoaded="{! c.onScriptsLoaded }" /> 

Component JavaScript Controller

onScriptsLoaded : function(component, event, helper) {
    var m = L.map(component.find('map').getElement(), {zoomControl: true,zoom:1,zoomAnimation:false,fadeAnimation:true,markerZoomAnimation:true}).setView([39.9537069, -75.1649369], 11);
    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
    }).addTo(m);
    component.set('v.map', m);
    helper.checkLoadingProgress(component, event, helper);
},

Note that the libraries are loaded asynchronously, and a named handler function in your controller is called when the library becomes available.

Each component is separated from its fellows, so you need to apply <ltng:require> in each component where you're making use of your external script file, and remember that you cannot count on the library being available until your afterScriptsLoaded handler gets called.

3

Have you tried uploading that JS file as a static resource and including it in your component markup via ltng:require? Then you will be able to reference any methods within that JS file in your Controller JS. Also notice that there is an afterScriptsLoaded parameter that could be used to call any method AFTER the script has been loaded.

<aura:component>
    <ltng:require scripts="{!$Resource.jsLibraries + '/jsLibOne.js'}" afterScriptsLoaded="{!c.doSomethingAfterScriptsLoaded}"/>

<!-- Do something here -->

</aura:component>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.