Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- https://andersanmiguel.com/diario-de-desarrollo-una-aplicacion-moderna-vanillajs-custom-elements -->
<test-component></test-component>
              
            
!

CSS

              
                
              
            
!

JS

              
                class BaseComponent extends HTMLElement {

  constructor() {
    super();
    // Call beforemount hook
    this.beforeMount();
  }

  // Component is injected to page
  connectedCallback() {
    // Load components if any
    this.loadComponents();
    // Render component
    this.render();

    // Call mounted hook
    this.mounted();
  }

  disconnnectedCallback() {
    // Call destroyed hook (clean event listeners an such)
    this.destroyed();
  }

  // Properties to watch, trigger render on attributeChangedCallback
  static get observedAttributes() {
    return this.properties;
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue !== newValue) {
      this.render();
    }
  }

  // Dynamic loading components
  loadComponents() {
    if (!this.components) {
      return;
    }
    this.components.forEach(this.importElement);
  }

   importElement(component) {
     
     // Esto lo he cambiado para esta demo porque los componentes aquí no se cargan
     // importándolos con una petición HTTP
    
      const exists = customElements.get(component.tagName);
      if (!exists) {
        if (!component.tagName) {
          throw Error(`Component ${ component.name } doesn't have tagName`);
        }
        customElements.define(component.tagName, component);
      }
   
  }

  // Optional hooks definitions
  beforeMount() {
    return;
  }
  mounted() {
    return;
  }
  destroyed() {
    return;
  }

  render(html, el) {

    // set defaults
    const htmlString = html || this.html;
    const container = el || this;
    // innerHTML, TODO: research if is needed
    const frag = document.createRange().createContextualFragment(htmlString);
    container.replaceChildren(frag);

  }

}

/* COMPONENTES DE EJEMPLO */
class ChildComponent extends BaseComponent {
  static tagName = 'child-component';
  // Siempre que cambia esta propiedad se renderiza otra vez el componente
  static properties = ['count'];
  get html() {
    return `<p>Child component, counter: ${ this.getAttribute('count') }</p>`
  }
}

class TestComponent extends BaseComponent {
  static tagName = 'test-component';
  // con esto cargo automáticamente el componente
  components = [ChildComponent];
  
  // propiedad de ejemplo, un contador
  count = 0;
  
  mounted() {
    // evento para incrementar el contador
    this.querySelector('#counter').addEventListener('click', e => {
      this.count++;
      // tengo que volver a renderizar el componente para que tenga efecto
      this.render();
      // y tengo que volver a crear el evento porque al renderizar lo he perdido 😭
      this.mounted();
    });
  }
  
  get html() {
    return `
      <p>Basic component</p>
      <button id="counter">Add one to child</button>
      <child-component count="${ this.count }"></child-component>
    `;
  }
}

customElements.define(TestComponent.tagName, TestComponent);

              
            
!
999px

Console