Search code examples
javascriptweb-componentcustom-element

Custom Elements: Can both a class and its super run a connectedCallback?


I have a class called QueryAddable

class QueryAddable extends HTMLElement {
  connectedCallback() {
    console.log('QueryAddable');
  }

It has several classes that extend it, such as

class QueryGroup extends QueryAddable {
  constructor() {
    super();
  }
  connectedCallback() {
    console.log('QueryGroup');
  }

Optimally, if I put <query-group> on the page, I'd like to see QueryAddable and QueryGroup logged in the console. I suppose it's not happening because I only have <query-group> on the page and not <query-addable>.

I could very well put a method in QueryAddable called onLoad and call that in the connectedCallback of each extending class, but why should I have to do it in multiple places instead of one?

Is there any way to get both connectedCallback functions to run, or is it setup so that only one can run?


Solution

  • class Parent extends HTMLElement {
      connectedCallback() {
        console.log('PARENT COMPONENT');
      }
    }
    
    class Child extends Parent {
      connectedCallback() {
        super.connectedCallback();
        console.log('CHILD COMPONENT');
      }
    }
    
    window.customElements.define('my-child', Child);
    <my-child></my-child>