聚合物2中只有就绪生命周期回调触发

时间:2017-05-11 20:28:28

标签: polymer web-component lifecycle polymer-2.x

当我创建Polymer 2.0元素时,只有ready生命周期回调似乎会触发,我无法解决原因。例如,我有这个Polymer元素:

<link rel="import" href="../../bower_components/polymer/polymer-element.html">

<dom-module id="flip-four-board">
    <script>
        class FlipFourBoard extends Polymer.Element {            

            static get is() { return "flip-four-board"; }

            created() {
                super.created();
                console.log("created");
            }

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

            attached() {
                super.attached();
                console.log("attached");
            }

            detached() {
                super.detached();
                console.log("detached");
            }

        }

        customElements.define(FlipFourBoard.is, FlipFourBoard);
    </script>

</dom-module>

但是当我把它插入这样的页面时:

<!DOCTYPE html>
<html>
<head>
    <title>Flip Four Board Tests</title>
    <script src="../../../bower_components/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="../../../bower_components/polymer/polymer.html">
    <link rel="import" href="../flip-four-board.html">
    <style type="text/css">
        html, body {
            width: 95%;
            height: 95%;
        }
    </style>
</head>
<body>
    <flip-four-board></flip-four-board>
</body>
</html>

控制台只读:

console log

为什么只有ready回调触发?

1 个答案:

答案 0 :(得分:20)

Polymer 2.0引入了几个lifecycle callback changes,包括在基于类的元素定义中替换除原始回调之外的所有回调(即ready)。在2.0中使用Polymer工厂方法时,旧版回调仍然可用。

      1.x (legacy)    |      2.x
----------------------|-----------------------------
    created           |   constructor
    attached          |   connectedCallback
    detached          |   disconnectedCallback
    attributeChanged  |   attributeChangedCallback
    ready             |   ready

所以,你的课应该看起来像这样:

class FlipFourBoard extends Polymer.Element {

  static get is() { return "flip-four-board"; }

  constructor() {
    super();
    console.log("created");
  }

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

  connectedCallback() {
    super.connectedCallback();
    console.log("attached");
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    console.log("detached");
  }

}

demo