JavaScript getter and setters

When using web components, a common task is to read attributes from the element.

The naive way is:

var Proto = Object.create(HTMLElement.prototype);
_.extend(Proto, {
  attachedCallback: function(){
    if(this.readAttributeAsJson('config-ready')){
      //do something
    }
  },
  readAttributeAsJson : function(name) {
    if(!this.hasAttribute(name)) { return false; }
    return JSON.parse(this.getAttribute(name));
  }
});
document.registerElement('vs-text', {
  prototype: Proto
});

The better way is:

var Proto = Object.create(HTMLElement.prototype, {
  configReady: {
    get: function(){ return this.readAttributeAsJson('config-ready'); }
  }
});
_.extend(Proto, {
  attachedCallback: function(){
    if(this.configReady){
      //do something
    }
  },
  readAttributeAsJson : function(name) {
    if(!this.hasAttribute(name)) { return false; }
    return JSON.parse(this.getAttribute(name));
  }
});
document.registerElement('vs-text', {
  prototype: Proto
});

Here we are using object getter and setters.

 

Another example where if you do a.id = 1, and then try to read a.id, you get 2

var _id = null;

var a = {};
Object.defineProperty(a, "id", {
 get: function() {
 console.log("get!");
 return _id;
 },
 set: function(value) {
 console.log("set!");
 _id = 2 * value; 
 } 
}); 
Standard

Polymer sequence of life cycle events

When you do this with a Polyer element

  created: function() {
    console.log('created');
  },
  ready: function() {
    console.log('ready');
  },
  attached: function () {
    console.log('attached');
  },
  domReady: function() {
    console.log('domReady');
  },
  detached: function() {
    console.log('detached');
  }

You get:

created
ready
attached
domReady
Standard

Requirejs inside web components

Summary:

The data-main attribute doesn’t work. You have to require manually.

 

This does NOT work:


<element name="vs-text">
   <link rel="stylesheet" href="vs-text.css">

   <template>
     <div class="main"></div>
   </template>

   <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js</span>" data-main="main"></script>

   <script src="vs-text.min.js"></script>
 </element> 

 

This works:

<element name="vs-text">
<link rel="stylesheet" href="vs-text.css">

<template>
<div class="main"></div>
</template>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js</span>"></script>
<script type="text/javascript">
require([], function() {
console.log('require');
});
</script>

<script src="vs-text.min.js"></script>
</element>

 

Standard