6

当我创建一个 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>

控制台只显示:

控制台日志

为什么只有ready回调触发?

4

1 回答 1

22

Polymer 2.0 引入了几个生命周期回调更改ready,包括替换基于类的元素定义中除了一个原始回调(即 )之外的所有回调。Polymer在 2.0 中使用工厂方法时,遗留回调仍然可用。

      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");
  }

}

演示

于 2017-05-11T21:46:36.133 回答