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">
import components from '$lib/components.ts';
import { getContextStore } from '$lib/stores/contextStore.ts';
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) {
if (components[componentName]) {
const module = await components[componentName]();

View File

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

View File

@ -1,6 +1,9 @@
<script>
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() {
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];
}