liveBook · Manning

Observedattributes

As explained in Web Components in Action

observedAttributes is a static custom-element class property or getter that specifies the attribute names monitored by attributeChangedCallback.

Configure a custom element by declaring which HTML attributes should trigger updates. observedAttributes limits attributeChangedCallback to changes the component actually needs. section 3.0 section 3.4

Declare observedAttributes as a static getter returning an array of attribute names. The browser calls attributeChangedCallback only when a changed attribute appears in that array. section 3.4

Use the pattern incrementally:

  • Choose attributes whose changes should affect component behavior, such as searchterm or layout. section 3.4 section 7.3
  • Return those names from the static observedAttributes getter; add more names as needed. section 3.4
  • Handle the matching name inside attributeChangedCallback and update the component. section 3.4

Reacting to a layout attribute

static get observedAttributes() { return ['layout']; }\n\nattributeChangedCallback(name, oldvalue, newvalue) {\n this.innerHTML = '';\n const template = document.getElementById(newvalue);\n this.appendChild(template.content.cloneNode(true));\n}\n\nChanging <biz-card layout="none"> through a menu selects and renders the matching template. Initial attribute values also trigger the callback. section 7.3

Listing 7.7. Simplified business card example using templates to drive HTML and CSS
export default class BizCard extends HTMLElement {
   static get observedAttributes() { return ['layout']; }

   attributeChangedCallback(                                 #1
       name, oldvalue, newvalue) {
       this.innerHTML = '';
       const template = document.getElementById(newvalue);
       const clone = template.content.cloneNode(true);
       this.appendChild(clone);
   }
}

if (!customElements.get('biz-card')) {
   customElements.define('biz-card', BizCard);
}

Inspect the compact template-driven component that observes layout and swaps its rendered content. section 7.3

How Web Components in Action covers it

How deep it goes
Explains the static getter, callback gate, and initial-value behavior, without detailing browser lifecycle internals.
Examples
Uses searchterm-driven searches and layout-driven business-card template selection.
What it assumes
Assumes custom-element and class basics while introducing selective attribute observation through practical examples.
What you can do after
Build it from scratch by declaring observed names and handling their changes in a custom element.
How it connects
Connects custom elements, HTML attributes, attributeChangedCallback, and HTML templates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.