1

Sorry, this may be a simple beginner question but I still get errors after following all instructions I could find.

I have a JS file (testjs.js), which I loaded in the resources as (testjs).

var hello = "Hello World!!!";

My component is as follow

<aura:component >
        <ltng:require scripts="{!$Resource.testjs}" afterScriptsLoaded="{!c.doInit}" />
</aura:component>

My controller is as follow

({

    doInit : function(component, event, helper) {
            console.log('Start');
            console.log(hello);
            console.log('End');

    }
})

When I run it, "Start" is displayed in the console. But it crashes at hello.

Action failed: c:Tryme$controller$doInit [hello is not defined]

Am I missing something? The console should display Hello World

1 Answer 1

2

Seems you cannot directly declare a variable in shared JS resource, but instead need to use a different pattern here as described in Sharing JavaScript Code Across Components guide.

This code uses the JavaScript module pattern. Using this closure-based pattern, the value variable remains private to your library. Components using the library can’t access value directly.

So in order to use the variable value in your component, you will need to declare a function which will return the value of the variable and define it as below in your JS in the static resource as below:

window._hello = (function() {
    var value = "hello world";

    return { 
        helloWorld: function() {
            return value;
        }
    };
}());

And then use it in your component as:

console.log(_hello.helloWorld());
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.