connectedCallback
A lifecycle hook called after the element is inserted into the document.
connectedCallback(props)
The browser calls a custom element's connectedCallback
when the element is added to the page. StacheElement uses this to set up the element's properties, render its view, and call the connected
lifecycle hook.
The connectedCallback
can also be called manually to trigger these things. For example, the following defines a greeting
property, uses it in the view
, and also programmatically adds a <p>
element in the connected
hook:
import { StacheElement } from "can/everything";
class MyElement extends StacheElement {
static view = `
<p>{{this.greeting}}</p>
`;
static props = {
greeting: { type: String, default: "Hello" }
};
connected() {
const p = document.createElement("p");
p.innerHTML = "World";
this.appendChild(p);
}
}
customElements.define("my-el", MyElement);
const myEl = new MyElement()
.connectedCallback();
myEl.greeting; // -> Hello
myEl.firstElementChild; // -> <p>Hello</p>
// <p>World</p>
Parameters
- props
{Object}
:The initial property values.
Returns
{Element}
:
The element
instance.
Purpose
StacheElement
implements the custom element connectedCallback
hook to:
- initialize the element with property values. These will be passed to
initialize
. - render the stache view into the element.
- connect the element to the DOM.
The connectedCallback
can be called to initiate these lifecycle methods. When creating an extended StacheElement
, the connectedCallback
should not be overwritten. Code that needs to run when an element is added to the page should be put in connected.