Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Events should subclass Event instead of using CustomEvents #1999

Open
justinfagnani opened this issue Apr 26, 2024 · 1 comment
Open

Events should subclass Event instead of using CustomEvents #1999

justinfagnani opened this issue Apr 26, 2024 · 1 comment
Assignees
Labels
bug Things that aren't working right in the library.

Comments

@justinfagnani
Copy link
Contributor

CustomEvents are a vestige of the DOM API from a time before Event was subclassable. Had JS allowed subclassing native object earlier, CustomEvent would have never existed.

All CustomEvents can instead be expressed as an event subclass, removing the need to use .detail.

For example, the SelectEvent defined here:

export type SlSelectEvent = CustomEvent<{ item: SlMenuItem }>;

declare global {
  interface GlobalEventHandlersEventMap {
    'sl-select': SlSelectEvent;
  }
}

and fired as:

this.emit('sl-select', { detail: { item } });

could instead be defined as:

export class SlSelectEvent extends Event {
  readonly item: MenuItem;

  constructor(item: MenuItem) {
    super('sl-select', {bubbles: true});
    this.item = item;
  }
}

declare global {
  interface GlobalEventHandlersEventMap {
    'sl-select': SlSelectEvent;
  }
}

and fired as:

this.dispatchEvent(new SelectEvent(item));

The custom constructor ensures that the event in created correctly every time, including options such as bubbling and composed (while emit() doesn't guarantee is consistent across dispatch sites). It's more ergonomic to use as well, and uses only built-in platform APIs to fire. emit() could be removed.

Because of the consistency guarantees, these event classes could be exported to 3rd party users to use in their own Shoelace-compatible components, without risk that they get the event options wrong.

@justinfagnani justinfagnani added the bug Things that aren't working right in the library. label Apr 26, 2024
@justinfagnani justinfagnani changed the title Events should subclass Event instead of using CUstomEvents Events should subclass Event instead of using CustomEvents Apr 26, 2024
@claviska
Copy link
Member

I believe doing this would let us get rid of most of this. If that's the case, I vote yes. However, I'd suggest we follow the event.detail pattern to prevent breaking changes.

@claviska claviska self-assigned this May 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Things that aren't working right in the library.
Projects
None yet
Development

No branches or pull requests

2 participants