Lifecycle

constructor

The constructor is called when the component is first created. This can be either when an element is created explicitly:

import Wafer from "@lamplightdev/wafer";

class MyExample extends Wafer() {
constructor() {
// the super constructor must always be called
super();

console.log("constructed");
}
}
customElements.define("my-element", MyExample);

const el1 = new MyExample();
// calls constructor
// logs `constructed`

const el2 = document.createElement("my-element");
// calls constructor
// logs `constructed`

or when an element is implicitly created when it is inserted into the DOM, either in JavaScript:

const div = document.querySelector("div");

div.innerHTML = "<my-element></my-element>";
// calls constructor, and connectedCallback
// logs `constructed`

or when parsed in HTML:

<div>
<my-example></my-example>
<!-- calls constructor, and connectedCallback when parsed -->
<!-- logs `constructed` -->
</div>

The constructor is also called if the element already exists in the DOM when the element becomes defined.

Specifying the use of Shadow DOM

By default Wafer components render their templates into a open shadow root. To specify a closed shadow root, the shadow argument can be used in the call to the super constructor:

class MyExample extends Wafer {
constructor() {
super({ shadow: "closed" });
}
}

To specify that the template should be rendered into the Light DOM a false value can be passed instead:

class MyExample extends Wafer {
constructor() {
super({ shadow: false });
}
}