Search code examples
polymerlit-element

Is there any better way to pass function to props with LitElement?


I'm using polymer LitElement and i tried to pass a function to props but did'nt work, this is the way i found to work, but its awfull... Any better suggestions?

import { LitElement, html, customElement, property } from 'lit-element';

@customElement('my-element')
export class MyElement extends LitElement {


onButtonClick = function name (){

  console.log("Clicked!!")
}

  render() {
    return html`

      <c-button text="Button Name" onClick="${this.onButtonClick}" />
    `;
  }
}

@customElement("c-button")
export class CButton extends LitElement{

  @property() text;
  @property() onClick;

  handleClick(){
    let fct = eval(`( ${this.onClick} )` )
    fct();
  }

  render(){
    return html`

      <button @click="${this.handleClick}" > ${this.text} </button> 
    `
  }
}


Solution

  • By default lit-html data bindings set an attribute which means it'll have to convert the value to a string.

    Instead of onClick="${this.onButtonClick}" prefix it with . like this .onClick="${this.onButtonClick}". That will set a property in JavaScript instead and the method will be passed by reference.