Skip to content

Instantly share code, notes, and snippets.

@JiaLiPassion
Last active June 22, 2018 13:45
Show Gist options
  • Save JiaLiPassion/86dae2a9d60a0aafd167ce46ed2c3bca to your computer and use it in GitHub Desktop.
Save JiaLiPassion/86dae2a9d60a0aafd167ce46ed2c3bca to your computer and use it in GitHub Desktop.
class AppHello extends HTMLElement {
  constructor() {
  super();
  }
  // define which attributes need to be observed so attributeChangedCallback will be triggered
  // when according attribute changed.
  static get observedAttributes() {return ['name']; }
  // getter to do a attribute -> property reflection
  get name() {
  return this.getAttribute('name');
  }
  // setter to do a property -> attribute reflection
  set name(val) {
  this.setAttribute('name', val);
  }
  connectedCallback() {
  this.div = document.createElement('div');
  this.text = document.createTextNode(this.name || '');
  this.div.appendChild(this.text);
  this.appendChild(this.div);
  }
  disconnectedCallback() {
  this.removeChild(this.div);
  }
  attributeChangedCallback(attrName, oldVal, newVal) {
  if (attrName === 'name' && this.text) {
  this.text.textContent = newVal;
  }
  }
}
customElements.define('hello-elem', AppHello);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment