Back to Lit

08

packages/lit-dev-content/site/tutorials/content/wc-to-lit/08.md

latest2.4 KB
Original Source

Button Functionality

And now finally, add some click event listeners to give the buttons functionality!

rating-element.<ts-js></ts-js>

{% switchable-sample %}

ts
export class RatingElement extends HTMLElement {
  ...
  private _boundOnUpClick = this._onUpClick.bind(this);
  private _boundOnDownClick = this._onDownClick.bind(this);

  connectedCallback() {
    ...

    this.shadowRoot!
      .querySelector('.thumb_up')!
      .addEventListener('click', this._boundOnUpClick);
    this.shadowRoot!
      .querySelector('.thumb_down')!
      .addEventListener('click', this._boundOnDownClick);
  }

  disconnectedCallback() {
    this.shadowRoot!
      .querySelector('.thumb_up')!
      .removeEventListener('click', this._boundOnUpClick);
    this.shadowRoot!
      .querySelector('.thumb_down')!
      .removeEventListener('click', this._boundOnDownClick);
  }

  ...

  _onUpClick() {
    this.vote = 'up';
  }

  _onDownClick() {
    this.vote = 'down';
  }
}
js
export class RatingElement extends HTMLElement {
  ...
  _boundOnUpClick = this._onUpClick.bind(this);
  _boundOnDownClick = this._onDownClick.bind(this);

  connectedCallback() {
    ...

    this.shadowRoot
      .querySelector('.thumb_up')
      .addEventListener('click', this._boundOnUpClick);
    this.shadowRoot
      .querySelector('.thumb_down')
      .addEventListener('click', this._boundOnDownClick);
  }

  disconnectedCallback() {
    this.shadowRoot
      .querySelector('.thumb_up')
      .removeEventListener('click', this._boundOnUpClick);
    this.shadowRoot
      .querySelector('.thumb_down')
      .removeEventListener('click', this._boundOnDownClick);
  }

  ...

  _onUpClick() {
    this.vote = 'up';
  }

  _onDownClick() {
    this.vote = 'down';
  }
}

{% endswitchable-sample %}

In this step you:

  • Bind some click listeners to the element (.bind(this)) and keep the references around as private class members.
  • Listen for click events on the <button>s in connectedCallback.
  • Clean up these listeners in disconnectedCallback.
  • Set this.vote appropriately in the click listeners themselves.

Congratulations, you now have a fully-featured web component; try clicking on some buttons!

The bad news now is that the element definition is around 100 lines, the HTML file is 38 lines, and the code is quite verbose, imperative, and unreadable for such a simple component. This is where Lit comes in!