Web component with invoker API

This is a combination of two relatively new web APIs: custom elements and the Invoker Commands API.

In this showcase, I show how you can make a custom element that can be controlled using any button, without having to manually hook up event listeners.

HTML structure:

<nav class="my-3">
    <button type="button" commandfor="color-box" command="--color-red">
        Red
    </button>
    <button type="button" commandfor="color-box" command="--color-blue">
        Blue
    </button>
    <button type="button" commandfor="color-box" command="--color-green">
        Green
    </button>
</nav>
<nia-color-box id="color-box"></nia-color-box>

JavaScript code:

class ColorBox extends HTMLElement {

  static {
    customElements.define('nia-color-box', this);
  }

  connectedCallback() {
    this.addEventListener('command', this.#onCommand);
  }

  disconnectedCallback() {
    this.removeEventListener('command', this.#onCommand);
  }

  #onCommand = event => {
    if (event.command === '--color-red') {
      this.style.setProperty('--box-color', '#FF4136');
    }
    else if (event.command === '--color-blue') {
      this.style.setProperty('--box-color', '#0074D9');
    }
    else if (event.command === '--color-green') {
      this.style.setProperty('--box-color', '#2ECC40');
    }
  };
  
}