packages/lit-dev-content/site/tutorials/content/wc-to-lit/08.md
And now finally, add some click event listeners to give the buttons functionality!
{% switchable-sample %}
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';
}
}
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(this)) and keep the references around as private class members.click events on the <button>s in connectedCallback.disconnectedCallback.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!