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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With