是否可以将 html 中的函数传递给 lit-element?

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

我见过将函数从父 lit-element 传递给子元素的示例,就像这里一样 - https://medium.com/@westbrook/litelement-to-do-app-1e08a31707a4

但我希望我的元素的用户不会被迫创建包装器元素来使用我的元素。

例如,我的元素是一个计算某些值的对话框。

我希望我能做这样的事情(html 使用我的元素):

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

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

然后在我的元素中:

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)
      }

当我尝试此操作时,出现 JavaScript 个错误。

您的元素代码没问题,您尝试设置函数的方式有点不对。

你看,如果你在 lit-html/lit-element 渲染函数中,你正在使用的语法将有效(只需进行一些更正,它将是 .resultingLatLong=${latLongResult}

但是,由于您在主级别的脚本中,您应该执行如下操作:

<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>

这是一个glitch,其中包含一个类似的最小示例

您还可以在 属性 resultingLatLonglat-long-chooser 中配置观察到的属性,并像这样设置 attribute: false

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

这将防止为 属性.

创建观察到的属性

由于您可以访问组件内部的 window 对象,另一种方法是传递函数的 name 并访问函数本身通过 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>
    `;
  }
});

然后在您的页面中:

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