简体   繁体   中英

Why are custom events preferred over attribute callbacks in web-components?

In web-components, similar to React, we send data down, and events up.

With React, it's common to send an event into a child component as an attribute. For example:

<CustomComponent handleClick={this.handleClick}></CustomComponent>

I've learned that it's also possible to do this with LitElement web-components:

<custom-component.handleClick=${this.handleClick}></custom-component>

However, many sources I've read say to use a custom event from within the component without ever mentioning attribute callbacks:

this.dispatchEvent(
    new CustomEvent('some-custom-event', {
        bubbles: true,
        composed: true,
        detail: {
            data: someData,
        },
    })
);

My question is, why is it preferred to dispatch a custom event rather than send a callback to the web component as an attribute? Is it convention or is there a strong reason that I just can't find?

If I understand your question correctly I believe the answer is that using event handlers vs passing a callback to a child component is to achieve a more loosely coupled architecture.

For example, in the situation where a callback is passed down, if the parent of the component in question did not implement (or pass) a callback then an error would be thrown when the child component tried to use it, whereas in the event handling situation there's likely less chance of errors if the parent just doesn't handle the event.

Probably more important than errors though it's often the case that a component is more flexible & easier to understand for other developers using it when using event handlers vs callbacks since it may require less understanding of the internal workings of the component.

There are exceptions to this of course but generally it's a best practice for more usable & well-designed components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM