定义一个 mixin
Docs: mixins , hybrid elements 。
定义类表达式 mixin 以在不同元素之间共享实现:
<script>
MyMixin = function(superClass) {
return class extends superClass {
// Code that you want common to elements.
// If you're going to override a lifecycle method, remember that a) you
// might need to call super but b) it might not exist.
connectedCallback() {
if (super.connectedCallback) {
super.connectedCallback();
}
/* ... */
}
}
}
</script>
在元素定义中使用 mixin:
<dom-module id="element-name">
<template><!-- ... --></template>
<script>
// This could also be a sequence:
// class MyElement extends AnotherMixin(MyMixin(Polymer.Element)) { … }
class MyElement extends MyMixin(Polymer.Element) {
static get is() { return 'element-name' }
/* ... */
}
customElements.define(MyElement.is, MyElement);
</script>
</dom-module>
使用混合行为(在 1.x 语法中定义)作为 mixins:
<dom-module id="element-name">
<template><!-- ... --></template>
<script>
class MyElement extends Polymer.mixinBehaviors([MyBehavior, MyBehavior2], Polymer.Element) {
static get is() { return 'element-name' }
/* ... */
}
customElements.define('element-name', MyElement);
</script>
</dom-module>