native web componet sample

by jpeter06

HTML

<my-element color="red" background="orange">aa</my-element>
<template id="templateMyElement">
  <div>
  MyElement: <slot></slot>
  </div>
  </div>
</template>

JavaScript

// MyElement  clase ES6  obligatoria
class MyElement extends HTMLElement {
	static get observedAttributes() {
    return ['color', 'bg'];
  }
  constructor() {
  //When created
    super();
    const shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `      
      <style>        
        .disabled {          
          opacity: 0.4;        
        }      
      </style>      
      <div id="container"></div>    
    `;
    this.container = this.shadowRoot('#container'); 
  }
  connectedCallback() {
    // here the element has been inserted into the DOM
    console.log("inserted");
  }
  disconnectedCallback(){
  	//Cuando nos desconectamos
  }
  
  //Cuando cambia un atributo
  //se ejecuta antes de connectedCallback
  attributeChangedCallback(attr, oldVal, newVal) {
  console.log("attr:",attr);
    switch(attr) {
      case 'color':
        // do something with 'foo' attribute
        console.log("color:",newVal)
      case 'bg':
        // do something with 'bar' attribute
        this.container.style.background=newVal;
    }
  }
  
  doSomething() {
    // do something in this method
  }
}
//Definición. el '-' es obligatorio
customElements.define('my-element', MyElement);