Skip to content

Lifecycle methods

George Treviranus edited this page Mar 24, 2022 · 10 revisions

Bulba provides a thin wrapper around the native custom element lifecycles. The purpose of these is to add more fidelity to the render lifecycle.

If you do choose to use the native callbacks directly, there is one caveat.

Methods

  • onConnect: Called at the beginning of connectedCallback, when the element has been attached to the DOM, properties have been upgraded (attributes and values available), but before the shadow root's HTML/styles have been rendered. Ideal for initializing any internal data, events, and/or kicking off async ajax requests.

  • onMount: Called at the end of connectedCallback, once the shadow root / DOM is ready. Ideal for registering DOM events or performing other DOM-sensitive actions. Note that this does not guarantee child shadow roots are rendered.

  • onUpdate: Called on each render after onMount. This includes: when a property updates or requestRender is called.

  • onPropertyChange(name, oldValue, newValue): Called each time a property gets changed. Provides the property name (as a string), the old value, and the new value. If the old value matches the new value, this method is not triggered. Create a custom property to customize this behavior.

  • onAttributeChange(name, oldValue, newValue): Called each time an attribute is changed. If the old value matches the new value, this method is not triggered. Set attributeChangedCallback with directly to customize this behavior.

  • onUnmount: Called by disconnectedCallback, right before the element's virtual DOM tree is deleted. Ideal for unregistering event listeners, timers, or the like.

Using Custom Element Lifecycle Callbacks

Bulba piggybacks off the native lifecycle callbacks, which means if you use them, you should also call super to get the custom logic added by the base class. This is especially true of connectedCallback and disconnectedCallback, which triggers the initial render and DOM cleanup steps, respectively.

Here's a quick reference for which methods and features are dependent on the native callbacks:

  • 🚨 connectedCallback: super required
    • Calls onConnect
    • Calls onMount
    • Also note if you override this method without super, no shadow root / styles / content will be rendered. :)
  • 🏳 attributeChangedCallback: super optional
    • Calls onAttributeChange
  • 🏳 adoptedCallback: super recommended (for compatibility in future versions)
  • 🚨 disconnectedCallback: super required
    • Calls onUnmount
Clone this wiki locally