Web - Component

> (World Wide) Web - (W3|WWW)

1 - About

Web Components are a set of features that provide a component model:

  • Custom Element – APIs to define new HTML elements
  • Shadow DOM – Encapsulated DOM and styling, with composition
  • HTML Templates, an HTML fragment is not rendered, but stored until it is instantiated via JavaScript[

2 - Example

2.1 - Custom Element

Taken from custom element

  • The HTML with a custom element defined with the is attribute
<p>Word Count example</p>
<!-- This custom element will count the words of the parent node -->
<p is="word-count"></p>
  • The definition of the custom element is in a class
// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();
 
    // count words in element's parent element
    const wcParent = this.parentNode;
 
    function countWords(node){
      const text = node.innerText || node.textContent;
      return text.split(/\s+/g).length;
    }
 
    const count = `Words: ${countWords(wcParent)}`;
 
    // Create a shadow root
    const shadow = this.attachShadow({mode: 'open'});
 
    // Create text node and add word count to it
    const text = document.createElement('span');
    text.textContent = count;
 
    // Append it to the shadow root
    shadow.appendChild(text);
 
    // Update count when element content changes
    setInterval(function() {
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count;
    }, 200);
  }
}
 
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
  • The result

Advertising

3 - Documentation / Reference

web/component.txt · Last modified: 2019/06/13 09:05 by gerardnico