lit-html

How to specify event handlers when using 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:


Solution

  • 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>`
    }