Svelte listens for any event on an element using the on:
directive. Customized events convey data between child and parent components. Components in Svelte can listen for DOM and custom events. The on:event-name
directive specifies how an event will be handled. It’s worth noting that the term ‘on’ comes after a comma and event name. Its value is the function that will be called after the event has been dispatched. The name of the event could be either DOM or custom. The specified function receives an event object.
In this shot, we learn about event handling.
Events are objects that serve as communication units between an emitter and the listeners. In short, any activity that happens on the HTML web page is an event. With the help of JavaScript (Svelte in this case), we can handle these events. Clicking a button or submitting are examples of events.
Example of a simple event:
<script>
function eventClickMe() {
// Handle something
}
</script>
<button on:click={eventClickMe}>Click Me</button>
In the App.svelte:
<script>
import EventComponent from './EventComponent.svelte';
</script>
<main>
<p> Event communication. </p>
<hr/>
<EventComponent />
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
When you load the application, it will look like the screenshot below:
You can see a button, but it will not do anything. Let’s add an alert only to check if our events are working correctly:
<script>
function eventClickMe() {
alert('I am clicked')
}
</script>
<button on:click={eventClickMe}>Click Me</button>
Here we see an Inline Event Handler.
<button on:click={ e => { alert('I am clicked') } }>
Click Me
</button>
Here is an alternate way of defining the Inline Event Handler
using the anonymous function on:click={ e => { alert('I am clicked') } }
Event dispatching allows developers to add logic to the Svelte application. We can dispatch events and communicate within the components using an event dispatcher. Components can forward events by creating and using an event dispatcher.
In the EventComponent.svelte
, we see the following:
<script>
import { createEventDispatcher } from 'svelte'
const dispatch = createEventDispatcher()
function eventClickMe() {
dispatch('message', {
text: 'Pass to main component'
});
}
</script>
<button on:click={eventClickMe}>
Click Me
</button>
The data given as the second argument to the dispatch function
is this object’s detail
property. Additional parameters supplied to dispatch are not considered.
In the App.svelte:
<script>
import EventComponent from './EventComponent.svelte';
function handleMessage(event) {
alert(event.detail.text)
}
</script>
<main>
<p> Event communication. </p>
<hr/>
<EventComponent on:message={handleMessage}/>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
Only the parent component receives these events. They don’t float to the top of the component hierarchy by themselves. The on:directive
is used by parent components to listen for events from child components.
We can modify the events in Svelte using these modifiers:
once
: removes the handler after the first time it runs.In the EventComponent.svelte, modify the button
with the code below:
<button on:click|once={eventClickMe}>
Click Me
</button>
You’ll notice that when you try to click the button a second time, it won’t show any alert.
preventDefault
: calls e.preventDefault()
before running the handler.When used with forms, it’ll prevent the default submission of forms.
stopPropagation
: Calls e.stopPropagation()
. It prevents the propagation of the events within the same handler.passive
: Improves scrolling performance.capture
: Fires the handler during the capture phase, not the bubbling phase.self
: only triggers the handler if event.target is the element itself.Only the parent component receives the event when we fire it, as discussed before. It won’t go to the hierarchy itself. However, sometimes, we need the events to be used by other parent components. We need to nest the events further up in the hierarchy.
Create a new file FirstEventComponent.svelte
. Modify the button
with the code below:
<script>
import { createEventDispatcher } from 'svelte'
const dispatch = createEventDispatcher()
function eventClickMe() {
dispatch('message', {
text: 'Pass to main component'
});
}
</script>
<button on:click|preventDefault={eventClickMe}>
Click Me
</button>
Create another file SecondEventComponent.svelte
. Modify the button
with the code below:
<script>
import FirstEventComponent from './FirstEventComponent.svlete';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function forward(event) {
dispatch('message', event.detail);
}
</script>
<FirstEventComponent on:message={forward} />
In the App.svelte:
<script>
import SecondEventComponent from './SecondEventComponent.svelte';
function handleMessage(event) {
alert(event.detail.text)
}
</script>
<main>
<p> Event communication. </p>
<hr/>
<SecondEventComponent on:message={handleMessage}/>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
<script> import { createEventDispatcher } from 'svelte' const dispatch = createEventDispatcher() function eventClickMe() { dispatch('message', { text: 'Pass to main component' }); } </script> <button on:click|preventDefault={eventClickMe}> Click Me </button>
Free Resources