2

How to distinguish between the Standard DOM event and the CustomEvent dispatched by LWC Component?

Assume we have some 2 simple LWС Components

<!--child.html-->
<template>
    <input type=text oninput={handleInput}>
</template>
// child.js
import { LightningElement } from 'lwc';
export default class Child extends LightningElement {
    handleInput(event) {
        this.dispatchEvent(new CustomEvent('input'));
    }
}
<!--parent.html-->
<template>
    <c-child oninput={handleInputParent}></c-child>
</template>
import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
    handleInputParent(event) {
        console.log('handle event');
    }
}
<!--app.html-->
<aura:application>
    <c:parent/>
</aura:application>

When I typed some symbol in my custom input field, console.log showed 'handle event' twice:

'handle event'
'handle event'

The LWC Dev Guide says that it happens because

Lightning web components dispatch standard DOM events. Components can also create and dispatch custom events.

How to override the Standard DOM event by CustomEvent of LWC Component?

If it is not possible so how can I distinguish between the Standard DOM event and the CustomEvent LWC in case if I don't want to create CustomEvent with the name that is different from the Standard DOM event name, (e.g. this.dispatchEvent(new CustomEvent('custominput') => oncustominput={handleInput}). The LWC Dev Guide says:

As a component author, you name the event type when you create the event. You can use any string as your event type. However, we recommend that you conform with the DOM event standard.

1 Answer 1

6

The Standard DOM event raised by LWC Component cannot be overridden by its CustomEvent which has the same name or not. It is also impossible to "mute" dispatching the Standard DOM events. However to distinguish between the Standard DOM event and the CustomEvent dispatched by LWC Component for the event listener Component you can use

The isTrusted read-only property of the Event interface is a Boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via EventTarget.dispatchEvent().

Or check whether (event instanceof CustomEvent) or not.

For instance in your case:

import { LightningElement } from 'lwc';

export default class Parent extends LightningElement {
    handleInputParent(event) {
        if (event.isTrusted) {
            console.log('handling standard DOM event');
        } else {
            console.log('handling CustomEvent');
        }

        // OR
        if (event instanceof CustomEvent) {
            console.log('handling CustomEvent');
        } else {
            console.log('handling standard DOM event');
        }
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .