2

Let's say I have a Lightning component client side controller that does some calculation on initialization based on attributes that were set but it isn't going to be rendered it's just internal information about the component. I don't want to create an attribute in the markup I just want to save it for later access in event handlers. What's the proper way to do that? I'm thinking something like this but there doesn't seem to be any documentation about it.

({
  doInit : function(cmp, event, helper) {
     var c = cmp.get("v.a") + cmp.get("v.b");
     cmp.setData("c",c);
  }
})

As a side not there is very little documentation on the javascript objects that are available and their usage in the lightning docs. Thanks for any help!

1 Answer 1

0

I would highly recommend an attribute. However, you can store things on the helper if you really really want to. This is probably not a best practice, and might cause breakage or be unreliable.

Think of this like a global static variable, it's not tied to an instance of your component.

Helper:

({
  c : {},
  doInit : function(cmp, event) {
     var c = cmp.get("v.a") + cmp.get("v.b");
     this.c = c;
  }
})

When you mutate this.c, you're actually manipulating the definition of your helper, not the instance of your component, so any other components of the same type should also see that value in this.c.

5
  • 2
    It will work in the Helper not in the controller.When you try to do this in the controller,you'll get this error Only functions are allowed in javascript controllers
    – Praveen
    Commented Jun 9, 2016 at 17:31
  • You can find more info about the Helper's behaviour here when component of the same type is used inside a container component as mentioned by @frontendloader
    – Praveen
    Commented Jun 9, 2016 at 17:56
  • so other than attributes defined in markup there's no way to store instance parameters? or is it acceptable to do cmp.set('v.param', 'value'); even if the attribute is not explicitly defined in the markup? Commented Jun 9, 2016 at 18:57
  • That should give you an access error when you attempt it. Commented Jun 9, 2016 at 19:07
  • As I understand it so far, there is no way to store computed data in the component itself. I maybe thinking about this wrong but what I'm trying to do is write a lighting component that will handle a large amount of data by only rendering what is visible in the viewport so as to not overload the dom. Commented Jun 9, 2016 at 20:57

You must log in to answer this question.

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