Is it possible to pass a function from html into a lit-element?

Viewed 4127

I have seen examples of passing a function from a parent lit-element to a child one like here - https://medium.com/@westbrook/litelement-to-do-app-1e08a31707a4

But I want the users of my element, not to be forced to create a wrapper element to use my element.

For example, my element is a dialog that computes some value.

I was hoping I could do something like this (html using my element):

<script>
 function latLongResult(lat,long)
    {
        console.log("resulting lat long called");
    }

</script>
    <lat-long-chooser id="latLongDialog" resultingLatLong=${latLongResult(lat,long)}></lat-long-chooser>

And then in my element:

export class LatLongChooser extends LitElement {


static get properties() {
    return {
      latDecimalDegrees: Number,
      longDecimalDegrees: Number,
      resultingLatLong: {
        type: Function,
      }
    };
  }

saveConvertedValues() {
       console.log("save other values called");
       this.resultingLatLong(this.latDecimalDegrees,this.longDecimalDegrees)
      }

When I try this, I get JavaScript errors.

3 Answers

Your element's code is fine, the way you're trying to set the function is what's a bit off.

You see, the syntax you're using would work if you were in a lit-html/lit-element render function (just with a few corrections, it would be .resultingLatLong=${latLongResult})

However, since you're in a script at the main level you should do something like this:

<script>
 function latLongResult(lat,long){
    console.log("resulting lat long called");
 }
 // do it like this so that it's set as a property, setting it as an attribute would require some rather complicated extra code
 document.querySelector('#latLongDialog').resultingLatLong = latLongResult;

</script>
<lat-long-chooser id="latLongDialog"></lat-long-chooser>

Here's a glitch with a minimal example of something similar in action

You can also configure a observed attributes, in your property resultingLatLong in your lat-long-chooser and set the attribute: false like that:

static get properties() {
    return {
      latDecimalDegrees: Number,
      longDecimalDegrees: Number,
      resultingLatLong: {
        type: Function,
        attribute: false
      }
    };
  }

This will prevent an observed attribute from being created for a property.

Since you've access to the window object inside your components another way to do this would be to pass the name of the function and access the function itself via window[functionName]:

customElements.define('my-example', class extends LitElement {
  static properties = {
    greet: {}
  }

  _greet() {
    window[this.greet]('Hello World!');
  }

  render() {
    return html`
      <button @click=${this._greet}>Greet</button>
    `;
  }
});

Then in your page:

<body>
  <my-example greet="greetHandler"></my-example>
  <script>
    function greetHandler(msg) {
      alert(msg);
    }
  </script>
</body>
Related