Polymer:如何在计算绑定中使用导入函数
Polymer: How to use imported function in computed binding
我想对不同自定义元素中的计算绑定使用共享函数。这可能吗?
无论我如何导入共享函数,我都会收到控制台错误:
method `formatAmount` not defined
计算绑定类似于:
<span>[[formatAmount(amount)]]</span>
我试过在元素上方使用标签。我已经在元素内部尝试过。我在 index.html.
中尝试过
是否所有计算绑定方法都需要在自定义元素中定义并且不能共享?我必须使用 mixin 吗?
更新:我创建了一个丑陋的解决方案,我在我的自定义元素上定义了一个调用共享方法的私有方法。然后在计算绑定中使用私有方法。这很难看,因为有额外的样板文件。
...
<script src="format-amount.js"></script>
<dom-module id="my-foo">
<template>
...[[_formatAmount(amount)]]...
</template>
<script>
class MyFoo extends Polymer.Element {
...
_formatAmount(amount) {
return formatAmount(amount); // Defined in format-amount.js.
}
}
</script>
</dom-module>
这与我几个月前问过的相似。
您可以使用 mixin
。 mixin
只是一个接受 class 和 returns 子 class 的函数。如果你想了解更多click here.
对于你的问题,在单独的 html 文件中定义 mixin
说 - my-mixin.html
:
const MyMixin = (superClass) => class extends superClass {
constructor() {
super();
}
formatAmount(amount) {
//function contents
}
}
然后在你的元素中导入并添加 mixin:
<link rel="import" href="my-mixin.html">
class MyFoo extends MyMixin(Polymer.Element)
然后您可以简单地从您的元素中调用该函数:
<template>
...[[formatAmount(amount)]]...
</template>
要访问脚本中的函数,请使用 super.formatAmount(amount)
。
我想对不同自定义元素中的计算绑定使用共享函数。这可能吗?
无论我如何导入共享函数,我都会收到控制台错误:
method `formatAmount` not defined
计算绑定类似于:
<span>[[formatAmount(amount)]]</span>
我试过在元素上方使用标签。我已经在元素内部尝试过。我在 index.html.
中尝试过是否所有计算绑定方法都需要在自定义元素中定义并且不能共享?我必须使用 mixin 吗?
更新:我创建了一个丑陋的解决方案,我在我的自定义元素上定义了一个调用共享方法的私有方法。然后在计算绑定中使用私有方法。这很难看,因为有额外的样板文件。
...
<script src="format-amount.js"></script>
<dom-module id="my-foo">
<template>
...[[_formatAmount(amount)]]...
</template>
<script>
class MyFoo extends Polymer.Element {
...
_formatAmount(amount) {
return formatAmount(amount); // Defined in format-amount.js.
}
}
</script>
</dom-module>
这与我几个月前问过的
您可以使用 mixin
。 mixin
只是一个接受 class 和 returns 子 class 的函数。如果你想了解更多click here.
对于你的问题,在单独的 html 文件中定义 mixin
说 - my-mixin.html
:
const MyMixin = (superClass) => class extends superClass {
constructor() {
super();
}
formatAmount(amount) {
//function contents
}
}
然后在你的元素中导入并添加 mixin:
<link rel="import" href="my-mixin.html">
class MyFoo extends MyMixin(Polymer.Element)
然后您可以简单地从您的元素中调用该函数:
<template>
...[[formatAmount(amount)]]...
</template>
要访问脚本中的函数,请使用 super.formatAmount(amount)
。