1

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?

  • Why don't you just leave it as const event = new CustomEvent('toggleeditasset'); That should work and you don't need to worry about anything else. – Nico W Aug 21 '19 at 13:03
  • I wanted to follow best practices where it says Use underscores to separate words. I'm aware I can do that, but I was more curious about how to do it the way the documentation says to do it – TemporaryFix Aug 21 '19 at 16:01
2

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);
};
| improve this answer | |

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.