According to the documentation on event dispatching event types should follow these rules:
- No uppercase letters
- No spaces
- Use underscores to separate words
When I attempt to use underscores in my event type I don't seem to be able to handle it.
Dispatcher:
<lightning-button label="Update" onclick={toggleEditAsset}></lightning-button>
toggleEditAsset = () => {
const event = new CustomEvent('toggle_edit_asset');
this.dispatchEvent(event);
}
Handler:
<c-asset-information asset={model.asset} edit-asset={editAsset} ontoggleeditasset={handleToggleEditAsset}></c-asset-information>
handleToggleEditAsset() {
this.editAsset = !this.editAsset
console.log('toggle');
}
This handler does not get called.
If I try to change ontoggleeditasset
to ontoggle_edit_asset
I get an error
LWC1056: Invalid event name ontoggle_edit_asset. Event name can only contain lower-case alphabetic characterslwc
If I change the event to toggleeditasset
everything works fine
What is the proper markup to handle an event with underscores?
Best Answer
If you want to handle an event type
sampleevent
in HTML of parent, you should directly add prefix in attributeonsampleevent
.But, You cannot add event handler in HTML with underscores
_
as it will not compile.However, you can do it through JS of parent component:
This is Playground link
This will work but you will be getting warning in the console as below:
IMPORTANT
You need to add
bubbles:true
in event as you need to Bubble an event up inside the containing component’s template.