Skip to content

[lit-element] Declarative event emitters #3277

@justinfagnani

Description

@justinfagnani

It would be convenient for ergonomics, documentation, React integration, and transpilers to be able to declare what events an element fires.

We could add a decorator (and static block for plain JS, like properties) that allows this by decorating event handler properties. The decorator would create accessors that use addEventListener under the hood.

TypeScript:

class MyElement extends LitElement {
  @event() onFoo!: (e: FooEvent) => any) | null;

  render() {
    html`<button @click=${this._onButtonClick}>Click Me</button>`;
  }

  _onButtonClick(e) {
    this.dispatchEvent(new FooEvent());
  }
}

interface HTMLElementEventMap {
  'foo': FooEvent;
}

JavaScript:

class MyElement extends LitElement {
  static events = {
    onFoo: {},
  };

  render() {
    html`<button @click=${this._onButtonClick}>Click Me</button>`;
  }

  _onButtonClick(e) {
    this.dispatchEvent(new FooEvent());
  }
}

See some similar previous discussion here: lit/lit-element#808

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

Status

📋 Triaged

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions