Week 6 | Lifecycle Callbacks

polymer 1.0
Mon Oct 03 2016

While declaring, attaching, adding and removing custom elements from from our page, these elements trigger some callback events. Polymer element’s callbacks are similar to the native Custom Element callbacks. Polymer adds only one new callback named “ready”.

So during the lifecycle of our element we have the following callbacks

created: Triggered once the element is created and not necessarily attached or loaded.

ready: when the properties are set, the data of the template has been copied and pasted in the element’s instance and all of the elements inside the local DOM are ready.

attached: after the element is attached to the document

detached: after the element is detached from the document.

attributeChanged: when one of the element’s attributes is changed.

factoryImpl:  is only invoked when you create an element using the constructor. For example:

 var el = new HelloElement();
document.querySelector("body").appendChild(el);
and not 

var el2 = document.createElement('hello-element'); 
document.querySelector("body").appendChild(el2);

For a full demo you can check out the following code or Plunkr page

 

    <button onclick="document.querySelector('hello-element').remove()">Remove Hello</button>
    <script>
      HTMLImports.whenReady(function () {
        HelloElement = Polymer({
          is: "hello-element",
          created: function() {
              this.textContent = "Hello there";
              console.log("Created: The element has been created.");
          },
          ready: function() {
              console.log("Ready: Property values set and local DOM is initialized.");
              this.message = "hello2";
          },
          attached: function() {
              console.log("Attached: The element is attached to the document." +
                  "Can be called multiple times.");
          },
          detached: function() {
              console.log("Detached: The element has been detached");
          },
          factoryImpl: function() {
              console.log("Factory Impl: Only invoked when creating an event using" + 
                  " the constructor.")
          },
          attributeChanged: function(attrName, oldVal, newVal) {
              console.log("AttributeChanged: Attribute " + attrName + 
                  " oldValue: " + oldVal + " newValue: " + newVal);
          }
        });
        
        var el = new HelloElement();
        document.querySelector("body").appendChild(el);
        var el2 = document.createElement('hello-element');
        document.querySelector("body").appendChild(el2);
      });
    </script>

 

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!