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?
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?
Share Improve this question asked Mar 31 at 20:53 AlexAlex 66.1k185 gold badges459 silver badges651 bronze badges 1 |1 Answer
Reset to default 2The 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
.)
update
function in the returned object to update. See the docs. – José Ramírez Commented Mar 31 at 21:01