是否可以将功能从html传递到浅色元素?

时间:2018-11-12 15:27:09

标签: javascript polymer 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错误。

2 个答案:

答案 0 :(得分:1)

您元素的代码很好,您尝试设置函数的方式有点麻烦。

您知道,如果您使用的是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,其中包含动作类似的最小例子

答案 1 :(得分:1)

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

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

这将防止为属性创建观察到的属性。

相关问题