Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
Combine svelte stores based on user input

I have the following svelte store:

export type SessionStore = {
   session?: Session,
   sessionType?: SessionType,
   inputs: []
}

The generation of the inputs field will change depending on the type of session:

  • If the session is of type 'local' it will be generated from the user's keyboard
  • If the session is of type 'online' it will be fed through network

I have a custom store that generates the session state based on the user's action:

function makeSessionStore() {
  const {subscribe, set, update} = writable(initialValue());

  return {
    subscribe,
    createLocalSession: () => update(() => ({
        session: {state: SessionState.RUNNING},
        sessionType: SessionType.LOCAL,
        inputs: [] // <--- how to generate this based on the session type?
    })),
    createNetworkSession: () => createSession().then(session => update(() => ({
        session,
        sessionType: SessionType.NETWORK,
        inputs: []
    })))
    reset: () => set(initialValue())
  }
}

My question: How can I attach a reactive store property to the inputs property?

This is e.g. how I get the inputs from the user's keyboard:

const keysPressed: Readable<string[]> = readable([], function(set) {
  let keys = [];

  const onKeydown = ({key}) => {
    if (keys.includes(key)) {
        return;
    }
    keys = [...keys, key];
    set(keys);
  }
  const onKeyup = ({key}) => {
    if (!keys.includes(key)) {
        return;
    }
    keys = keys.filter(k => k !== key);
    set(keys);
  }

  document.addEventListener('keydown', onKeydown);
  document.addEventListener('keyup', onKeyup);

  return () => {
    document.removeEventListener('keydown', onKeydown);
    document.removeEventListener('keyup', onKeyup);
  }
})

I would like the components using the inputs to be unaware of the strategy switching behind the scenes, they should be able to use the inputs like this:

import {sessionStore} from './session';
console.log($sessionStore.inputs) // ['CONTROL', 'w']
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I ended up using slotted components instead of stores for this problem.

Basic idea: Wrap the input depending component(s) in wrappers, that define the input type.

{#if !session}
    <h1>no session</h1>
{:else if session.type === SessionType.LOCAL}
    <LocalSessionWrapper let:inputs={inputs}>
        <slot inputs={inputs}></slot>
    </LocalSessionWrapper>
{:else}
    {#if session.state === SessionState.PENDING}
        <h3>waiting for other player...</h3>
    {:else if session.state === SessionState.CLOSED}
        <h3>game over!</h3>
    {:else if session.state === SessionState.RUNNING}
        <NetworkSessionWrapper let:inputs={inputs}>
            <slot inputs={inputs}></slot>
        </NetworkSessionWrapper>
    {:else }
        <h3>unknown game state</h3>
    {/if}
{/if}

The wrapper components use stores to define the source of input:

LocalSessionWrapper:

<script lang="ts">
    import {localSessionInputs, Session} from "./game/session";

    export let session: Session;
</script>

<slot inputs={$localSessionInputs}></slot>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda