【问题标题】:Create a polymer element using an ES6 class?使用 ES6 类创建聚合物元素?
【发布时间】:2016-04-13 02:47:03
【问题描述】:

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

然而,Polymer 似乎忽略了类的生命周期方法。以下代码不运行#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

【问题讨论】:

    标签: class ecmascript-6 polymer-1.0


    【解决方案1】:

    有一个article for using ES6 with Polymer in the docs


    因此,您缺少 2 件事:

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

    我是这样做的:

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

    注意:

    • 上面的 sn-p 只适用于 Chrome/FF
    • 对于其他所有内容,您当然可以“babelize”它。

    【讨论】:

    • 是的,我最终找到了这篇文章。有一个重要的陷阱——你不能在类上定义任何属性。您必须在#beforeRegister 中的“this”对象上定义它们......这非常令人困惑。
    • 这里也一样,但我很快就掌握了窍门
    • 是的,我正在使用 Polymer 编写一个框架......这意味着其他开发人员(以及奇怪的错误)的学习曲线。必须编写一个帮助程序来验证 Polymer 类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多