0
0
Svelteframework~5 mins

Action with event dispatching in Svelte

Choose your learning style9 modes available
Introduction

Actions let you add custom behavior to HTML elements easily. Dispatching events from actions helps communicate changes back to the component.

You want to add reusable behavior to an element, like focusing or dragging.
You need to notify the component when something happens inside the action.
You want to keep logic outside the component but still react to it.
You want to create custom events from native DOM events.
You want to clean up event listeners automatically when the element is removed.
Syntax
Svelte
function myAction(node) {
  const handle = () => {
    node.dispatchEvent(new CustomEvent('myEvent', { detail: { info: 'hello' } }));
  };

  node.addEventListener('click', handle);

  return {
    destroy() {
      node.removeEventListener('click', handle);
    }
  };
}

The node parameter is the HTML element the action is applied to.

Use node.dispatchEvent to send custom events from the action.

Examples
This action focuses the element when it is created.
Svelte
function focusAction(node) {
  node.focus();
  return {
    destroy() {
      // cleanup if needed
    }
  };
}
This action dispatches a 'notify' event when the element is clicked.
Svelte
function clickNotify(node) {
  const onClick = () => {
    node.dispatchEvent(new CustomEvent('notify', { detail: { clicked: true } }));
  };
  node.addEventListener('click', onClick);
  return {
    destroy() {
      node.removeEventListener('click', onClick);
    }
  };
}
Sample Program

This Svelte component uses an action called highlight that toggles a yellow background on the button when clicked. It also dispatches a custom event toggled with the current state. The component listens to this event and updates a message below the button.

Svelte
<script>
  function highlight(node) {
    const handleClick = () => {
      node.classList.toggle('highlighted');
      node.dispatchEvent(new CustomEvent('toggled', { detail: { highlighted: node.classList.contains('highlighted') } }));
    };

    node.addEventListener('click', handleClick);

    return {
      destroy() {
        node.removeEventListener('click', handleClick);
      }
    };
  }

  let message = 'Not highlighted';
  function onToggled(event) {
    message = event.detail.highlighted ? 'Highlighted!' : 'Not highlighted';
  }
</script>

<style>
  .highlighted {
    background-color: yellow;
  }
  button {
    padding: 0.5rem 1rem;
    font-size: 1rem;
  }
</style>

<button use:highlight on:toggled={onToggled} aria-pressed={message === 'Highlighted!'}>
  Click me
</button>
<p>{message}</p>
OutputSuccess
Important Notes

Always remove event listeners in the destroy method to avoid memory leaks.

Custom events can carry data in the detail property.

Use semantic HTML and ARIA attributes for accessibility, like aria-pressed on toggle buttons.

Summary

Actions add reusable behavior to elements.

Dispatch custom events from actions to communicate with components.

Clean up event listeners in the destroy method.