Hello World Example

Rafał Lorenz edited this page May 17, 2017 · 4 revisions

For example to create HelloWorld component and use it in your index.html file as follow:

<hello-world who="Unicorn"></hello-world>

You could setup component like shown below:

  1. Template file hello-world.html
<h1>Hello<span id="who"></span>!</h1>
  1. Javascript file hello-world.js
import { WebComponent } from 'web-component'

@WebComponent('hello-world', {
  template: require('./hello-world.html'),
  shadowDOM: true
})
export class HelloWorld extends HTMLElement {
  constructor() {
    super();
    this._who = null; //this property is bind to element attribute becouse of observedAttributes
  }

  static get observedAttributes() {
    return ['who'];
  }

  // Only called for the who attributes due to observedAttributes
  attributeChangedCallback(name, oldValue, newValue) {
    //this._who = newValue; this is handled by WebComponent decorator
    this._updateRendering();
  }

  connectedCallback() {
    // this is handled by WebComponent decorator
    // if (this.hasAttribute('who')) {
    //   this._who = this.getAttribute('who');
    // }
    this._updateRendering();
  }

  // Decorator creates setter/getter methods for observed attributes
  //we do not have to do this

  // get who() {
  //   return this._who;
  // }

  // set who(v) {
  //   this.setAttribute("who", v);
  // }

  _updateRendering() {
    this.shadowRoot.querySelector('#who').textContent = `, ${this._who}`;
  }
}
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.