javascriptsvelteactionsvelte-component

Parameters in svelte action not reactive


Svelte action that does things when keys are pressed:

import type { Action } from "svelte/action"

export const keys: Action<HTMLElement, boolean> = (node, active?: boolean) => {

  function listener(event: KeyboardEvent & { currentTarget: EventTarget & Window }) {
    if(!active){ // <- always initial value
      return;
    }

    const target = event.target as HTMLElement
    if(target instanceof HTMLInputElement){
      return;
    }

    // do things with node...
  }

  window.addEventListener("keydown", listener, true)

  return {
    destroy() {
      window.removeEventListener("keydown", listener, true)
    }
  }
}

it's used in components like this:

<div use:keys={someLocalStateVar} ...

Problem is that the active argument which corresponds to someLocalStateVar does not change when the state changes.

Is there a way to make it reactive in the action?


Solution

  • The value is copied once, so it will not change.

    Actions can return an update function that is called if a parameter changes, so you could do:

    return {
        update(newActive) { active = newActive },
        destroy() {
            window.removeEventListener("keydown", listener, true)
        },
    }
    

    Playground

    Note that another feature is currently in the works that might supersede actions soon: Attachments

    You can also avoid the update function by passing in a function pointing to the state instead.

    <div use:keys={() => localActiveState}>
    
    export const keys: Action<HTMLElement, boolean> = (node, getActive?: () => boolean) => {
        function listener(event: KeyboardEvent & { currentTarget: EventTarget & Window }) {
            if (getActive != null && getActive() == false) {
                return;
            }
            ...
    

    Playground

    (Here the state is only used in events, so no "real" reactivity is needed, but in scenarios where this is the case, you can also use the function approach in combination with an $effect.)