पाठ 11 / 25

Element Bindings and Actions

bind: on elements and use: for DOM behaviour.

Two-way element bindings and actions

Bindings keep state and element properties in sync: bind:value on inputs, textareas and selects (numeric inputs give numbers), bind:checked for checkboxes, bind:group for radio or checkbox groups, bind:this for a reference to the DOM node, and read-only dimension bindings such as bind:clientWidth. An action is a function (node, parameter) applied with use:name={param}; it runs when the element mounts and can return update and destroy methods. Actions are a good place for reusable DOM behaviour such as click-outside, tooltips or focus traps. Newer Svelte 5 versions also add attachments ({@attach}) as a more flexible alternative; check the docs for your version.

Bindings plus a click-outside action

A dropdown.

<script lang="ts">
  function clickOutside(node: HTMLElement, onOutside: () => void) {
    const handle = (e: MouseEvent) => {
      if (!node.contains(e.target as Node)) onOutside();
    };
    document.addEventListener('click', handle, true);
    return {
      update(next: () => void) { onOutside = next; },
      destroy() { document.removeEventListener('click', handle, true); }
    };
  }

  let open = $state(false);
  let size = $state('m');
  let qty = $state(1);
  let width = $state(0);
</script>

<div use:clickOutside={() => (open = false)} bind:clientWidth={width}>
  <button onclick={() => (open = !open)}>Options ({width}px wide)</button>
  {#if open}
    <label><input type="radio" bind:group={size} value="s" /> Small</label>
    <label><input type="radio" bind:group={size} value="m" /> Medium</label>
    <input type="number" min="1" bind:value={qty} />
  {/if}
</div>
<p>{qty} x size {size}</p>

An action is a plug-in for an element

Like clipping a light onto a bike: the bike works without it, the light attaches when mounted and you take it off when you are done.

त्वरित जाँच: What should an action return to clean up listeners when the element is removed?

  • Nothing; Svelte removes listeners automatically
  • A Promise
  • A $state value
  • An object with a destroy method
Answer

An object with a destroy method — Actions control their own setup and teardown.