Events in Svelte

series on svelte part 4

ยท

4 min read

Events in Svelte

Hey folks ,welcome back to new episode in the series of svelte ,till now we have covered introduction , setup condition based statements and loops .

Before Events lets see what is reactivity or reactive statements means ?.

Svelte automatically updates the DOM when some component's state changes. So,if we want some piece of code to be executed when a component's state change then Reactivity comes into play. These parts are computed whenever state of component change. Reactive elements are denoted by

$: reactive_statements An example for better understanding.


<script>
    let count = 0;
    $: doubled = count * 2;
    function handleClick() {
        count += 1;
    }
</script>

<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}

</button>
<p>{count} doubled is {doubled}</p>

We click on button count changes and double value is dependent on count variable so it is evaluated by its own whenever DOM updates and changes the value of double (reactive variable )

We can specify any statement as reactive statement ,it may be console something or some alert or some function in the similar way.

Lets jump to the events

Events : events are the things that directly triggers some function or process on something ,means there is some action happens when something is triggered--it is somewhat confusing lets understand with basic example of clicking a button

<script>
    let count = 0;

    function handleClick() {
         alert("on click event")
    }
</script>

<button on:click={handleClick}>
    Click me
</button>

on:click is an event which triggers a function handleClick when we click on that button. there are similar events like mouseover ,mouseup(down) etc .

There are something called as events modifier ,event modifier are generally used to change the natural behaviour of particular event. Some of the vent modifiers are given below

  • stopPropagation
  • passive
  • nonpassive
  • self
  • once
  • trusted

each one of them has some special meaning and are defined to perform some special tasks over event , they can be run in chain as well like on:click|once|capture={...}.

Component event

Components can also dispatch events. They must create an event dispatcher and what does this mean dispatching events-- :) In simple words we can define events in some other component and can handle them from some other component where the earlier one was used.

Lets say we have App.svelte which is importing another component hello.svelte , so we can dispatch an event in hello.svelte and can use it when we call hello.svelte in App.svelte (this is called listening of event )

How can we dispatch an event from one component to another ?

We use a dispatcher provided by svelte itself , with help of dispatch function of dispatcher we can define a dispatch value and event .

hello.svelte

    <script>
    import { createEventDispatcher } from 'svelte';
     //importing dispatcher from svelte
    const dispatch = createEventDispatcher();
   //initialising dispatch function so that we can use

    function doSomething() {
        dispatch('message', {
            text: 'hey buddy!'
        }); // dispatch function creates an event  also a value to dispatch
    }
</script>
<p on:click={doSomething}> Hey i am th para.</p>

We define our dispatcher in hello.svelte which contains a

tag having an event on click which triggers a function doSomething when para. is clicked , this function dispatches name of the event and value also here value is an object.

now we have to catch/use this dispatching values so when we call hello.svelte, we pass a on: handler to it. lets discuss through an example

<script>
    import Hello from './hello.svelte';

    function handleMessage(event) {
        alert(event.detail.text); // gives text value
    }
</script>

<Hello on:message={handleMessage}/>

While Hello.svelte in App.svelte defines a on: handler for the event,we are also getting the dispatched value of that event . The function handleMessage can use that value as event.detail.text In this manner component events are used.

Event forwarding can also be done using component events.Also we can pass an event as Props to child component but we have to define it in the child component as

//in parent component
<Button on:click={handleClick}/>
<button on:click> 
<!-- we have define on: click here which was passed as props from parent -->
    Click me
</button>

We got a new word called Props, we will look into next part

That's all for today .. :) Thanks for reading part 4! I hope it has been a helpful read. Please leave any questions or comments below. Don't forget to like and share the article if it helps you in any way. Stay curious, cheers!