dispatch

Sends a CustomEvent from the host.

dispatch(type: string, detail?: unknown, options?: CustomEventInit): boolean
function select(item) {
  if (dispatch("select", { id: item.id })) state.selected = item.id;
}

Parameters

Parameter Type Default Meaning
type string required Event name
detail any undefined event.detail
options CustomEventInit { bubbles: true, composed: true, cancelable: true } Overrides any of the defaults

Returns false if a listener called preventDefault() (or a handler attribute returned false), otherwise true.

Handling the event

Where How
A parent component's markup <child-tag onselect="choose(event.detail)">
A plain page <child-tag onselect="…"> or element.onselect = fn. REALM finds names written as dispatch("name" in the script. See on… handlers
JavaScript element.addEventListener("select", …)

Example

Previewindex.htmlcolor-picker.html
Red Green Blue none
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>dispatch demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/dist/theme.css">
  <script type="module" src="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.js"></script>
</head>
<body>
  <import-element from="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/components/button.html"></import-element>

  <import-element from="./color-picker.html"></import-element>

  <color-picker onpick="document.getElementById('picked').value = event.detail.color"></color-picker>
  <output id="picked">none</output>
</body>
</html>
<custom-element name="color-picker">
  <script>
    function pick(color) {
      dispatch("pick", { color });
    }
  </script>

  <style>
    :host {
      display: inline-flex;
      gap: calc(var(--spacing) * 2);
    }
  </style>

  <ui-button variant="outline" onclick="pick('red')">Red</ui-button>
  <ui-button variant="outline" onclick="pick('green')">Green</ui-button>
  <ui-button variant="outline" onclick="pick('blue')">Blue</ui-button>
</custom-element>

Edit this page on GitHub · View as Markdown