[SalesForce] LWC Event handler for event type with underscores

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 attribute onsampleevent.

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:

I would recommend not to create event-types with underscores as it may not even be supported from javascript in future releases (although currently it is able to handle)

connectedCallback() {
    this.template.addEventListener('toggle_edit_asset', this.handleToggle);
}
handleToggle(e) {
    console.log('toggle_edit_asset handled');
}

This is Playground link

This will work but you will be getting warning in the console as below:

[LWC warning]: Invalid event type "toggle_edit_asset" dispatched in element . Event name should only contain lowercase alphanumeric characters.

IMPORTANT

You need to add bubbles:true in event as you need to Bubble an event up inside the containing component’s template.

toggleEditAsset = () => {
    const event = new CustomEvent('toggle_edit_asset', { bubbles: true });
    this.dispatchEvent(event);
};
Related Topic