Events
This documentation is a work in progress. It describes prerelease software, and is subject to change.
In this step, you’ll use lit-html’s @event
annotation to add an event listener to an element inside your template.
Starting code
my-element.js
/**
* Try LitElement https://lit-element.polymer-project.org/try
* Starting code for 5. Events
*/
import { LitElement, html } from '@polymer/lit-element';
class MyElement extends LitElement {
static get properties() {
return {
message: { type: String },
myBool: { type: Boolean },
myArray: { type: Array }
};
}
constructor() {
super();
this.message='Hello world! From my-element';
this.myArray = ['an','array','of','test','data'];
this.myBool = true;
}
render() {
return html`
<p>${this.message}</p>
<ul>
${this.myArray.map(item => html`<li>${item}</li>`)}
</ul>
${this.myBool?
html`<p>Render some HTML if myBool is true</p>`:
html`<p>Render some other HTML if myBool is false</p>`}
<!-- TODO: Add an event listener. -->
<button>Click</button>
`;
}
/**
* TODO: Implement an event handler.
*/
}
customElements.define('my-element', MyElement);
-
Add an event listener.
In my-element.js, in your template, replace the existing HTML
button
element with the following code:<button @click="${this.clickHandler}">Click</button>
The annotation above adds a listener for the
click
event. -
Implement an event handler.
To handle the
click
event, define the following method on yourMyElement
class:clickHandler(event) { console.log(event.target); this.myBool = !this.myBool; }
If you’re stuck, click Launch Code Editor below to see the completed code for Step 5.