2

Is it possible to preserve a JavaScript variable between component calls of the client-side code?

For example, after a third party library in my component loads I am calling a function in the controller. That function creates a variable.

Then after a specific event is handled by the same component I am calling a function from the same controller as above. And here I would like to be able to access the variable.

2
  • This sounds like it would just be a private attribute of the component. Am I misunderstanding?
    – David Reed
    Commented Aug 2, 2018 at 19:03
  • Agree with David. Lightning is stateful on the client side, so why can't you assign that JS variable to an aura:attribute and use it whenever needed? That value is preserved as long as the component is not destroyed/refreshed. Commented Aug 2, 2018 at 19:13

1 Answer 1

5

You're allowed to store attributes on the global "window" object if you need to. Each component gets its own "SecureWindow" object, so your global variables can't affect other components.

However, the preferred method would be to set a private attribute:

<aura:attribute name="someAttr" type="someType" access="private" />

...

component.set("v.someAttr", someValue);

...

var someValue = component.get("v.someAttr");

You can use whichever method makes the most sense. Also remember that you can use closures and Promises to temporarily store a value while chaining asynchronous callbacks.

2
  • So, did I get it correctly? Writing something like: window.myCustomAttribute = {}; in lightning controller is safe and allowed.
    – iloveseven
    Commented Aug 2, 2018 at 19:19
  • @iloveseven Yes, that's correct. You are allowed to use it if you want to.
    – sfdcfox
    Commented Aug 2, 2018 at 19:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .