Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte / SvelteKit 'before:event'?

I have a custom Form.svelte component, which has its own submit handler, however I would like to expose this somewhat, to allow me to have a specific function run before the submit function is called.

A simplified version:

Form.svelte

<script>
const handleSubmit = async () => {
  // Do things
}
</script>

<form on:submit={handleSubmit} class="new-form">
   <slot />
</form>

customers/new/+page.svelte

<script lang="ts">
type Customer = { postcode: string, shipping_postcode: string };

let duplicateAddress = false;
const customer = { postcode: "", shipping_postcode: "" };

const beforeSubmit = () => {
  if (duplicateAddress) customer.shipping_postcode = customer.postcode;

  if (!customer.postcode) {
     // Throw an error, for example.
  }
}
</script>

<Form before:submit={beforeSubmit} data={customer}>
  <input type="text" bind:value={customer.postcode} placeholder="Postcode" />
  <input type="checkbox" bind:checked={duplicateAddress} />
</Form>

Is this possible and, if so, how do I implement this?

like image 926
Basil Avatar asked Dec 30 '25 04:12

Basil


1 Answers

You could create an event dispatcher and emit your own event called e.g. beforeSubmit and give it a handler with on:beforeSubmit where you use the component:

<!-- Form.svelte -->
<script>
  import { createEventDispatcher } from 'svelte';

  const dispatch = createEventDispatcher();
    
  const handleSubmit = async () => {
    dispatch('beforeSubmit');

    // Do things
  }
</script>

<form on:submit={handleSubmit} class="new-form">
   <slot />
</form>

<!-- customers/new/+page.svelte -->
<script lang="ts">
  // ...

  const beforeSubmit = () => {
    // ...
  }
</script>

<Form on:beforeSubmit={beforeSubmit} data={customer}>
  <input type="text" bind:value={customer.postcode} placeholder="Postcode" />
  <input type="checkbox" bind:checked={duplicateAddress} />
</Form>
like image 180
Tholle Avatar answered Dec 31 '25 17:12

Tholle