Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify event handlers when using lit-html?

Tags:

lit-html

The main documentation under [Writing Templates] the following example for binding an event handler with lit-html is provided.

html`<button @click=${(e) => console.log('clicked')}>Click Me</button>`

Adding this a simple page with the default render and html functions imported and calling render however doesn't seem to render the button. If you remove the @click event binding then the button is rendered. There must be something I'm missing or a serious bug in the library.

version: 0.10.2

The links below relate to how events handler bindings work in lit-html:

  • https://polymer.github.io/lit-html/guide/writing-templates.html
  • https://github.com/Polymer/lit-html/issues/399
  • https://github.com/Polymer/lit-html/issues/145
  • https://github.com/Polymer/lit-html/issues/273
  • https://github.com/Polymer/lit-html/issues/146
like image 614
jpierson Avatar asked Aug 13 '18 02:08

jpierson


1 Answers

The previous accepted answer was wrong. lit-extended is deprecated and that workaround only worked for a period in 2018 while lit-html was switching over to the new syntax.

The correct way to consume an event is:

html`<button @click=${e => console.log('clicked')}>Click Me</button>`

You can configure the event by assigning an object with a handleEvent method too:

const clickHandler = {

    // This fires when the handler is called
    handleEvent(e) { console.log('clicked'); }

    // You can specify event options same as addEventListener
    capture: false;
    passive: true;
}

html`<button @click=${clickHandler}>Click Me</button>`

There is also lit-element which gives you a base for building web components with Lit and TypeScript enhancements to move the boilerplate noise of creating event handlers into decorators:

@eventOptions({ capture: false, passive: true })
handleClick(e: Event) { console.log('clicked'); }

render() {
    return html`<button @click=${this.handleClick}>Click Me</button>`
}
like image 146
Keith Avatar answered Oct 20 '22 11:10

Keith