Exploring the capabilities of Svelte as a newcomer, I am attempting something that may or may not be achievable, but I remain optimistic! 😄
Within a component, I have a delete button that triggers a globally accessible modal to appear as a confirmation dialog. This modal component is located in my __layout.svelte
file so that it can be called from any part of my application.
//=== Modal.svelte ===
<script lang="ts">
import { modal, confirmTrash } from '$lib/stores/modal'
//Perform various customizations to the modal...
</script>
{#if modal.show}
<h2>{$modal.title}</h2>
<p>{$modal.message}</p>
<button on:click={() => { send confirmation that the delete was confirmed }>{$modal.button}</button>
{/if}
Below is the modal
store structure:
//=== modal.ts ===
import { writable } from 'svelte/store'
//Adjust the state of the modal
export const modal = writable({
title: '',
message: '',
button: '',
mode: '',
show: false
})
//Simple function to display the trash confirmation modal
export function confirmTrash(modalTitle: string, modalMessage: string, buttonText: string){
modal.set({
title: modalTitle,
message: modalMessage,
button: buttonText,
mode: 'trash',
show: true
})
}
Lastly, in one of my app components, I trigger the deletion process by clicking a link that prompts the delete confirmation modal to appear:
//=== Component.svelte ===
<script lang="ts">
import { confirmTrash } from '$lib/stores/modal'
</script>
<a href="#trash"
on:click={() => {
confirmTrash('Trash Title', 'Message goes here.', 'Delete', function(result){
//Desire to receive feedback on whether the user clicked "Delete" should be handled here
console.log(result) //???
})
}}
>Trash</a>
I'm seeking clarity on how to establish a callback function within my confirmTrash
method to transmit the user's response in the modal back to the point where the modal was activated. Is this achievable?