attributeChangedCallback lets a custom element react when a watched HTML attribute is added, removed, or changed. It turns declarative markup changes into component behavior, such as rerunning a search or changing a layout. section 3.0 section 3.4
Wire the callback into a custom element in three steps:
- Declare the attributes to monitor with static get observedAttributes(), such as ['searchterm']. section 3.4
- Define attributeChangedCallback(name, oldValue, newValue); the browser supplies the changed attribute name and its previous and current values. section 3.4
- Branch on name and update only the relevant behavior; an unobserved attribute does not trigger this callback. section 3.4
- Account for startup ordering: initial attributes can invoke attributeChangedCallback before connectedCallback, so dependent DOM nodes may not exist yet. section 3.6
Rerun a search when searchterm changes
A text input updates the component with setAttribute('searchterm', event.target.value). The observed attribute then invokes attributeChangedCallback, which checks for 'searchterm' and calls doSearch(). Removing the separate startup search avoids overlapping requests when both lifecycle callbacks would run. section 3.4
Drive a slider and card layout
A slider observes value and backgroundcolor, dispatching each new value to refreshSlider or setColor. A business-card component observes layout, clears its contents, clones the matching template, and appends it when the attribute changes. section 3.6 section 7.3
Listing 3.12. AttributeChangedCallback to listen for changes to our searchterm
attributeChangedCallback(name, oldval, newval) {
if (name === 'searchterm') {
this.doSearch();
}
}
Open the minimal callback that reruns a component search when searchterm changes. section 3.4
