Skip to content

Commit

Permalink
fix:MultiSelect on:change triggered twice
Browse files Browse the repository at this point in the history
  • Loading branch information
jumtp committed May 6, 2024
1 parent 6ff61d2 commit b725e5d
Showing 1 changed file with 9 additions and 22 deletions.
31 changes: 9 additions & 22 deletions src/lib/forms/MultiSelect.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import CloseButton from '$lib/utils/CloseButton.svelte';
import { twMerge } from 'tailwind-merge';
import type { FormSizeType, SelectOptionType } from '../types';
import { createEventDispatcher } from 'svelte';
const dispatcher = createEventDispatcher();
export let items: SelectOptionType<any>[] = [];
export let value: (string | number)[] = [];
export let size: FormSizeType = 'md';
export let dropdownClass: string = '';
export let placeholder: string = '';
let selectItems: SelectOptionType<any>[] = items.filter((x) => value.includes(x.value));
$: selectItems = items.filter((x) => value.includes(x.value));
let show: boolean = false;
const sizes = {
Expand Down Expand Up @@ -38,40 +40,25 @@
const selectOption = (select: SelectOptionType<any>) => {
if (value.includes(select.value)) {
clearThisOption(select);
} else {
if (!value.includes(select.value)) value = [...value, select.value];
} else if (!value.includes(select.value)) {
value = [...value, select.value];
dispatcher('change');
}
};
const clearAll = (e: MouseEvent) => {
e.stopPropagation();
value = [];
dispatcher('change');
};
const clearThisOption = (select: SelectOptionType<any>) => {
if (value.includes(select.value)) {
value = value.filter((o) => o !== select.value);
dispatcher('change');
}
};
function create_custom_event(type: string, detail: any, { bubbles = false, cancelable = false } = {}) {
return new CustomEvent(type, { detail, bubbles, cancelable });
}
function init(node: HTMLSelectElement, value: any) {
const inital = value; // hack for below
return {
update: (value: any) => {
selectItems = items.filter((x) => value.includes(x.value));
// avoid initial event emitting
if (value !== inital) {
node.dispatchEvent(create_custom_event('input', selectItems));
node.dispatchEvent(create_custom_event('change', selectItems));
}
}
};
}
// Keyboard navigation
function handleEscape() {
if (show) {
Expand Down Expand Up @@ -126,7 +113,7 @@
</script>

<!-- Hidden select for form submission -->
<select use:init={value} {...$$restProps} {value} hidden multiple on:change on:input>
<select {...$$restProps} {value} hidden multiple on:input>
{#each items as { value, name }}
<option {value}>{name}</option>
{/each}
Expand Down

0 comments on commit b725e5d

Please sign in to comment.