Only ready lifecycle callback fires in Polymer 2
Asked Answered
R

1

6

When I create a Polymer 2.0 element, only the ready lifecycle callback seems to fire, and I can't work out why. For example, I have this Polymer element:

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

But when I insert it into a page like this:

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

The console only reads:

console log

Why is only the ready callback firing?

Relator answered 11/5, 2017 at 20:28 Comment(1)
It looks like you need to read the Polymer 2.0 upgrade guide.Dyan
C
22

Polymer 2.0 introduces several lifecycle callback changes, including the replacement of all but one of the original callbacks (i.e., ready) in the class-based element definitions. The legacy callbacks are still available when using the Polymer factory method in 2.0.

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

So, your class should look similar to this:

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

Cureall answered 11/5, 2017 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.