Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created August 3, 2024 22:59
Show Gist options
  • Save guiseek/dc207a43a842e4ffe1fabc2e14f92e9d to your computer and use it in GitHub Desktop.
Save guiseek/dc207a43a842e4ffe1fabc2e14f92e9d to your computer and use it in GitHub Desktop.
merge form input events
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