lit-element icon indicating copy to clipboard operation
lit-element copied to clipboard

Declarative event emitters

Open justinfagnani opened this issue 4 years ago • 11 comments

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: https://github.com/Polymer/lit-element/issues/808

justinfagnani avatar Feb 12 '20 17:02 justinfagnani