Observed Attributes

Web ComponentsCustom Elements

attributeChangedCallback() 在解析 HTML 完後就會自動執行不需另外在 constructor 中強迫執行❗️

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.
  }
}

Last updated