Replies: 2 comments 4 replies
-
It works fine. Test it the Svelte REPL here. You can also inspect implementation in your node_modules. See /**
* @param {EventTarget} element
* @param {string} type
* @param {EventListener} handler
* @param {AddEventListenerOptions} [options]
*/
export function on(element, type, handler, options = {}) {
var target_handler = create_event(type, element, handler, options);
return () => {
element.removeEventListener(type, target_handler, options);
};
} I'm not sure when you say "force to a I'm also not sure why you're creating listeners in an effect. It could be what you actually want to do to for some reason, but I somehow very thoroughly doubt it? |
Beta Was this translation helpful? Give feedback.
-
If we add these two declarations we can get the correct typings for both window and document /**
* Attaches an event handler to the document and returns a function that removes the handler. Using this
* rather than `addEventListener` will preserve the correct order relative to handlers added declaratively
* (with attributes like `onclick`), which use event delegation for performance reasons
*
* */
export function on<Type extends keyof DocumentEventMap>(document: Document, type: Type, handler: (this: Document, event: DocumentEventMap[Type]) => any, options?: AddEventListenerOptions | undefined): () => void;
/**
* Attaches an event handler to the window and returns a function that removes the handler. Using this
* rather than `addEventListener` will preserve the correct order relative to handlers added declaratively
* (with attributes like `onclick`), which use event delegation for performance reasons
*
* */
export function on<Type extends keyof WindowEventMap>(window: Window, type: Type, handler: (this: Document, event: WindowEventMap[Type]) => any, options?: AddEventListenerOptions | undefined): () => void; |
Beta Was this translation helpful? Give feedback.
-
I was trying to add a simple keyboard command
and usually you bind keyboard events against either the window or the document.
to be able to handle cleanup easier I wanted to use svelte/events on function.
but the generic parameter says the first param should be a decendant of HTMLElement, which window and document don't seem to be which causes the second param to not be of type KeyboardEvent.
I was able to get around it by forcing it to be a HTMLElement, but that seems bad
Are we not supposed to use
on
for window and document?or is it that the typescript types needs updating to include window and document?
Beta Was this translation helpful? Give feedback.
All reactions