Reader small image

You're reading from  Real-World Svelte

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804616031
Edition1st Edition
Languages
Right arrow
Author (1)
Tan Li Hau
Tan Li Hau
author image
Tan Li Hau

Tan Li Hau is a frontend developer at Shopee and a core maintainer of Svelte. He has delivered multiple conference talks and workshops on Svelte. Passionate about sharing his knowledge, Li Hau regularly contributes to the community through blog posts, YouTube videos, and books. He aspires to inspire others to explore and learn about Svelte and other modern web technologies.
Read more about Tan Li Hau

Right arrow

Custom Events with Actions

Actions are one of the most powerful features of Svelte.

They are a lightweight alternative to a component that encapsulates logic and data into a reusable unit. They help us reuse the same logic on different elements.

While components have life cycle methods such as onMount and onDestroy that run when all the elements within the component are added to or removed from the DOM, actions are designed to handle the logic for individual elements, running only when that specific element is added to or removed from the DOM.

While components can receive and react to prop changes, you can pass data to actions from a parent component to a child component. The actions will react when the data is changed and you can specify how the action should react when that data changes.

Actions are simple yet amazingly versatile. You can use them for various things. In this and the following chapters, we are going to explore some of the use cases of actions.

One of...

Technical requirements

You can find the projects of the chapter here: https://github.com/PacktPublishing/Real-World-Svelte/tree/main/Chapter05

Defining actions

Before we start to talk about using Svelte actions to create custom events, let’s quickly recap how to define an action in Svelte.

In Svelte, an action is nothing but a function that follows an action contract. This means if a function follows a specific function signature, it is considered an action. Here is the function signature of an action:

function action(node) {
  return {
    destroy() {}
  };
}

It is a function that optionally returns an object that has a destroy method.

In this case, since the action function follows the action contract, it is a Svelte action.

To use the Svelte action on an element, you can use the use: directive:

<div use:action />

Here, we used the Svelte action named action on the div element.

So, what will happen to the div element with a Svelte action?

When the <div> element is mounted to the DOM, Svelte will call the action function with the reference...

Reusing DOM event logic with custom events

Before we start talking directly about actions, let’s look at an example of using the mousedown and mouseup events to create a long-press behavior. We shall see how this simple example will lead us on to Svelte actions:

<script>
  let timer;
  function handleMousedown() {
    timer = setTimeout(() => {
      console.log('long press!');
    }, 2000);
  }
  function handleMouseup() {
    clearTimeout(timer);
  }
</script>
<button
  on:mousedown={handleMousedown}
  on:mouseup={handleMouseup}
/>

In the preceding example, we tried to implement a long-press behavior in a button. The idea is to press and hold the button for more than two seconds and then perform some action. As we detect it’s a long press, we print 'long press!' into...

Example – validating form inputs with custom events

The example that we are going to explore is using actions to validate form inputs.

When you add an input element to your form, you can add attributes such as required, minlength, and min to indicate that the input value has to pass the constraint validation or else would be considered invalid.

However, by default, such a validation check is only done during form submission. There’s no real-time feedback on whether your input is valid as you type.

To make the input element validate as you type, we need to add an 'input' event listener (which will be called on every keystroke as we type in the input element) and call input.checkValidity() to validate the input. Now, let’s do just that:

<input on:input={(event) => event.target.checkValidity()} />

As you call the checkValidity() method, if the input is indeed invalid, then it will trigger the 'invalid' event:

<input...

Exercise – creating a drag-and-drop event

A drag-and-drop behavior means clicking on an element, moving the mouse while holding down the click to drag the element across the screen to the desired location, and then releasing the mouse click to drop the element in the new location.

A drag-and-drop behavior thus involves coordination between multiple events, namely, 'mousedown', 'mousemove', and 'mouseup'.

As we perform the drag-and-drop motion, what we are interested in knowing is when the dragging starts, how far the element is dragged, and when the dragging ends.

These three events can be translated into three custom events: 'dragStart', 'dragMove', and 'dragEnd'.

Let us try to implement the drag-and-drop behavior as an action that will create these three custom events:

<div
  use:dragAndDrop
  on:dragStart={...}
  on:dragMove={...}
  on:dragEnd={...}
/>
...

Summary

In this chapter, we saw how to define an action. We talked about one of the common patterns of actions, which is to create custom events. This allows us to encapsulate DOM event logic into custom events and reuse them across elements.

In the next chapter, we will look at the next common pattern of actions, which is integrating third-party libraries.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Real-World Svelte
Published in: Dec 2023Publisher: PacktISBN-13: 9781804616031
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Tan Li Hau

Tan Li Hau is a frontend developer at Shopee and a core maintainer of Svelte. He has delivered multiple conference talks and workshops on Svelte. Passionate about sharing his knowledge, Li Hau regularly contributes to the community through blog posts, YouTube videos, and books. He aspires to inspire others to explore and learn about Svelte and other modern web technologies.
Read more about Tan Li Hau