Any simple way to share constants between helper methods in a Lightning Component?
Yes, we can take help of inheritance;
baseComponent.cmp
<aura:component extensible="true">
<!-- more content here like Attributes/Event -->
{!v.body}
</aura:component>
baseComponentHelper.js
({
constants: {
'ADD_ACTION': 'ADD',
'EDIT_ACTION': 'EDIT'
},
/* some more reusable methods like(server calling) */
})
anotherComponent.js
<aura:component extends="c:baseComponent">
<!-- more content here -->
{!v.body}
</aura:component>
anotherComponentController.js
({
onRowAction : function(component, event, helper) {
var action = event.getParam('action');
switch(action.name) {
case helper.constants.ADD_ACTION:
...
case helper.constants.EDIT_ACTION:
...
}
},
})
anotherComponentHelper.js
({
onRowAction : function(component, event, helper) {
var action = event.getParam('action');
switch(action.name) {
case this.constants.ADD_ACTION:
...
case this.constants.EDIT_ACTION:
...
}
},
})
You could use ltng:require to import a static resource. Of course, this has the drawback that such constants won't be available on init
, but it would be available shortly after. The constants would be available in both your helper and controller.
Another alternative would be to use Custom Labels, just like you'd use in Visualforce; the $Label value provider will allow you to get those values in init
if you need to. Again, you can use them in both the controller and helper.
Both of these designs presume that you don't want to have to deal with inheritance, particularly because you can't extend more than one component (it's not a "mixin" system like in Ruby).