4

How do I use a JavaScript object as an aura:attribute?

Should I do it this way <aura:attribute name="jsObj" type="Object" default="{aValue: 5}"/> or another?

  • whats your use case for using type "object" , you can accomplish most use cases using built in aura attribute types – RedDevil Jun 19 '18 at 18:34
  • I have a tooltip on hovering in one component. I have another component in which a user can change the text displayed in the tooltip by typing his/her own text in the input field. For the visualization I am using svg d3.js. So, what I would like to do now is to pass a JavaScript svg object with a reference to a tooltip object to the component in which the user can change the text of the tooltip. And then when the user changes the text I would update it using the reference passed. it is the best communication I was able to come up with between components in the case. – oobarbazanoo Jun 19 '18 at 18:39
6

As Kris Gray (@GrayJustise) pointed out on Twitter once, Object is a simple Object, and Lightning doesn't know what to do with it, so it does this only safe thing it can: it makes it a String. Instead, use a Map, which tells Lightning that you have a key-value pair in there you're trying to parse:

<aura:attribute name="jsObj" type="Map" default="{'aValue': 5}"/>

Note that you should be using JSON-like syntax (e.g. quoting strings, etc). Lightning will try to do the right thing if you specify Map, but most likely will not if you specify Object. Note that this only applies to the default attribute. If you are setting the attribute inside of a method (via component.set), it doesn't matter which you use:

<aura:attribute name="jsObj" type="Object" />

init: function(component, event, helper) {
  component.set("v.jsObj", { aValue: 5 });
}

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.