Creating your events in Svelet components

What’s interesting is that we can create custom events in components, and use the same syntax of built-in DOM events.

To do so, we must import the createEventDispatcher function from the svelte package and call it to get an event dispatcher:

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()
</script>

Once we do so, we can call the dispatch() function, passing a string that identifies the event (which we’ll use for the on: syntax in other components that use this):

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()

  //when it's time to trigger the event
  dispatch('eventName')
</script>

Now other components can use ours using

<ComponentName on:eventName={event => {
  //do something
}} />

You can also pass an object to the event, passing a second parameter to dispatch():

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()
  const value = 'something'

  //when it's time to trigger the event
  dispatch('eventName', value)

  //or

  dispatch('eventName', {
    someProperty: value
  })
</script>

the object passed by dispatch() is available on the event object.

Leave a comment

Your email address will not be published. Required fields are marked *