finished correct decoupling of action with svelte stores

This commit is contained in:
Samuel Andert 2023-07-22 18:11:20 +02:00
parent dc3995e327
commit 68708b65d8
5 changed files with 28 additions and 6 deletions

View File

@ -1,7 +1,13 @@
<script lang="ts"> <script lang="ts">
import components from '$lib/components.ts'; import components from '$lib/components.ts';
import { getContextStore } from '$lib/stores/contextStore.ts';
export let componentsData = []; export let componentsData = [];
// For each component, get or create its context store
componentsData.children.forEach((child) => {
child.store = getContextStore(child.componentName);
});
async function getComponent(componentName) { async function getComponent(componentName) {
if (components[componentName]) { if (components[componentName]) {
const module = await components[componentName](); const module = await components[componentName]();

View File

@ -1,15 +1,18 @@
<script> <script>
import SendMessage from './SendMessage.svelte'; import { getContextStore } from '$lib/stores/contextStore.ts';
import ClearMessages from './ClearMessages.svelte';
const store = getContextStore('MessageInput');
let newMessageText = ''; let newMessageText = '';
function handleKeyDown(event) { function handleKeyDown(event) {
if (event.key === 'Enter') { if (event.key === 'Enter') {
newMessageText = ''; // Clear the input after sending the message newMessageText = '';
event.preventDefault(); event.preventDefault();
} }
} }
// Reactive assignment to store when newMessageText changes
$: store.set({ newMessageText });
</script> </script>
<footer class="flex justify-end p-4 bg-white"> <footer class="flex justify-end p-4 bg-white">
@ -20,6 +23,4 @@
bind:value={newMessageText} bind:value={newMessageText}
on:keydown={handleKeyDown} on:keydown={handleKeyDown}
/> />
<SendMessage bind:newMessageText />
<ClearMessages />
</footer> </footer>

View File

@ -1,6 +1,9 @@
<script> <script>
import { createMessage } from '$lib/services/messages'; import { createMessage } from '$lib/services/messages';
export let newMessageText = ''; import { getContextStore } from '$lib/stores/contextStore.ts';
const store = getContextStore('MessageInput');
$: newMessageText = $store.newMessageText; // bind newMessageText from the store
function handleSend() { function handleSend() {
if (newMessageText.trim() !== '') { if (newMessageText.trim() !== '') {

View File

@ -0,0 +1,12 @@
// /lib/stores/contextStore.ts
import { writable } from 'svelte/store';
const createStore = () => writable({});
const contextStore = {};
export const getContextStore = (componentName) => {
if (!contextStore[componentName]) {
contextStore[componentName] = createStore();
}
return contextStore[componentName];
}