# Observed Attributes

[Web Components](https://lochiwei.gitbook.io/web/component) ⟩ [Custom Elements](https://lochiwei.gitbook.io/web/component/custom-element) ⟩

{% tabs %}
{% tab title="📘 手冊" %}

* Google ⟩ Custom Elements ⟩ [Observing changes to attributes](https://developers.google.com/web/fundamentals/web-components/customelements#attrchanges)
  {% endtab %}

{% tab title="⬇️ 應用" %}

* [Box](https://lochiwei.gitbook.io/web/css/layout/system/box)
  {% endtab %}
  {% endtabs %}

{% hint style="info" %}
**attributeChangedCallback**() 在解析 HTML 完後就會**自動執行**，**不需**另外在 **constructor** 中強迫執行❗️
{% endhint %}

```javascript
class AppDrawer extends HTMLElement {

  // Reflecting properties to attributes
  get disabled() {
    return this.hasAttribute('disabled');
  }

  set disabled(val) {
    if (val) {
      this.setAttribute('disabled', '');
    } else {
      this.removeAttribute('disabled');
    }
  }
  
  // ⭐️ observed attributes
  static get observedAttributes() {
    return ['disabled', 'open'];
  }

  // ⭐️ attributes changed
  // ⭐️ (only called for the observed attributes)
  attributeChangedCallback(name, oldValue, newValue) {
    // When the drawer is disabled, update keyboard/screen reader behavior.
    if (this.disabled) {
      this.setAttribute('tabindex', '-1');
      this.setAttribute('aria-disabled', 'true');
    } else {
      this.setAttribute('tabindex', '0');
      this.setAttribute('aria-disabled', 'false');
    }
    // TODO: also react to the open attribute changing.
  }
}
```
