Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How do I pass a value to a svelte.ts file?

$
0
0

I am currently creating an Svelte 5 app using Konva.
This is what the component looks like:

<!-- Canvas.svelte --><script lang="ts">    import { Stage, Rect, Layer, Line } from 'svelte-konva';    import { generateGrid, getPadding } from '$drawingTools/grid.svelte';    import { createRect, handleDragend } from '$drawingTools/rectangle.svelte';    import { zoom, dragNav } from '$drawingTools/navigation.svelte';    import { rectangle } from '$drawingTools/shapes/classes.svelte';    import { handleKeyDown } from '$drawingTools/undoRedo.svelte';    let height: number = $state(window.innerHeight);    let width: number = $state(window.innerWidth);    let rects: rectangle[] = $state([]);    let grid: any = $state();    let padding: number = $derived(getPadding());    let undoRedoMemory: rectangle[] = $state([]);    $effect(() => {        grid = [];        grid = generateGrid(width, height, padding);    });</script><Stage    {height}    {width}    draggable={true}    onclick={(e) => rects.push(createRect(e))}    onwheel={zoom}    ondragmove={(e) => {        dragNav(e, width, height, padding);    }}><Layer>        {#each grid as line}<Line {...line} />        {/each}        {#each rects as rect, index}<Rect                {...rect}                draggable={true}                ondragend={(e: any) => handleDragend(e, rect, index, rects)}            />        {/each}</Layer></Stage><svelte:window onkeydown={handleKeyDown} />

In order to keep my code clean, I want to keep the functions inside of .svelte.ts files, like this one for example:

// undoRedo.svelte.ts// something like import { rects, undoRedoMemory } from 'Canvas.svelte'export function handleKeyDown(e: KeyboardEvent) {    if ((e.ctrlKey && e.key === 'z') || e.key === 'Z') {        deleteLatest();    }    if ((e.ctrlKey && e.key === 'y') || e.key === 'Y') {        readdLatest();    }}function deleteLatest() {    let latest = rects.length - 1;    if (latest >= 0) {        undoRedoMemory.push(rects[latest]);        rects.pop();    }}function readdLatest() {    let latest = undoRedoMemory.length - 1;    if (latest >= 0) {        rects.push(undoRedoMemory[latest]);        undoRedoMemory.pop();    }}

In this case, I'd like to export the undoRedoMemory to the undoRedo.svelte.ts file in order for the functions to work with the array without having to pass it to each current and yet to come functions manually.

Apparently I am supposed to use the $props() rune, but I can't seem to wrap my head around it.
Also I am rather new to application development and this is my first bigger project, so if I am missing any fundamental point here, please enlighten me.


Viewing all articles
Browse latest Browse all 1541

Trending Articles