Created
August 3, 2024 22:59
-
-
Save guiseek/dc207a43a842e4ffe1fabc2e14f92e9d to your computer and use it in GitHub Desktop.
merge form input events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Callback<T> { | |
(value: T): void; | |
} | |
function merge<T>(form: HTMLFormElement) { | |
const watchers = new Set<Callback<T>>(); | |
const fields = Array.from(form.elements) as HTMLInputElement[]; | |
const value = <T>(form: HTMLFormElement) => { | |
const data = new FormData(form); | |
return Object.fromEntries(data.entries()) as T; | |
}; | |
for (const element of fields) { | |
element.addEventListener("input", () => { | |
for (const watcher of watchers) { | |
watcher(value<T>(form)); | |
} | |
}); | |
} | |
return { | |
subscribe(callback: Callback<T>) { | |
watchers.add(callback); | |
return { | |
unsubscribe() { | |
watchers.delete(callback); | |
}, | |
}; | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment