使用 ES6 class 创建聚合物元素?

Create a polymer element using an ES6 class?

我希望能够创建一个 class 以传递给 Polymer 函数来创建元素。明显的用例是有一个基础 class,我们的开发人员可以使用它来构建 Polymer 元素。

但是,Polymer 似乎忽略了 class 上的生命周期方法。下面的代码没有运行#created。有解决方法吗?

//attempt 1
class CustomElement {

  is = 'sample-multi-view-polymer-buic'

  created() { console.log('created') } // never called
}

export default Polymer(new CustomElement()) // doesn't work (see error below)

由于我使用 Babel 将 ES6 转换为 ES5,所以上面的代码等同于下面的代码。也不行。

 // attempt2
function CustomElement() {

  this.is = 'sample-multi-view-polymer-buic'
}

CustomElement.prototype.created= function() { console.log('hi') } //never called

有个article for using ES6 with Polymer in the docs


所以你这边缺少两件事:

  • 您缺少 beforeRegistered() 方法。
  • 您需要使用 Polymer() 实例化元素的 Class。

这是我的做法:

<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<link href="paper-input/paper-input.html" rel="import">

<dom-module id="x-example">

  <template>
    <paper-input value="{{name::input}}"></paper-input>
    <h4>{{name}}</h4>
  </template>
  
  <script>
    "use strict";

    class xExample {

      beforeRegister() {
        this.is = "x-example";
        this.properties = {
          name: {
            type: String,
            value: "I'm a data-binded prop"
          }
        }
      }

      ready() {
        console.log("ready");
      }
    }

    Polymer(xExample);
  </script>

</dom-module>

<x-example></x-example>

注:

  • 以上代码片段仅适用于 Chrome/FF
  • 对于其他一切你当然可以 "babelize" 它。