7

This question has been raised before but I haven't seen a satisfactory answer to it.

Basically I want to make global variable (which is a chart object reference) available to all components (for event handlers etc to have access to the object).

If I switch locker services off I can simply graft the object reference into the aura $A global

$A.netChart = new NetChart({
            container: ctx,
           area: { height: 350 }, 
 ...

But going forward this wont be a viable option with locker services being mandated.

The other suggestion is to use a custom global value provider:

myChart = new chart(); 
$A.set('myChartObject', myChart);

But lightning doesn't currently support custom global value providers and the above causes an exception to be thrown.

Am I missing something? Is there a way to make the global chart variable available?

3

How about using static resources and defining the global variables like below

Approach 1 involves using a static resource file to store all the global values

Here is how a code in your static resource look like

(function(w){
  "use strict"; //Optional because LC on LockerService active runs in strict mode

 var globalConstants = {
    "variable1":"abc",
    "variable2":"zyz"
  };

  w.globalvalues = globalConstants;

})(window);

And then in lightning component you will use like below

 ltng:require scripts="{!$Resource.TestScript}" afterScriptsLoaded="{!c.afterScriptsLoaded}" />

 afterScriptsLoaded : function(cmp){
   globalvalues.variable1; 
   globalvalues.variable2; 
 }

Approach 2: An application event fired on init call and all the components handle it .

| improve this answer | |

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.