|
17 | 17 |
|
18 | 18 | let text: TextComponent; |
19 | 19 | let styles: CSSObject = {}; |
20 | | - let textChangeHandler: ((event: Event) => void) | null = null; |
| 20 | + let inputHandler: ((event: Event) => void) | null = null; |
| 21 | + let changeHandler: ((value: string) => void) | null = null; |
21 | 22 |
|
22 | 23 | onMount(() => { |
23 | 24 | text = new TextComponent(textRef); |
24 | | -
|
25 | | - textChangeHandler = (event: Event) => { |
26 | | - const newValue = (event.target as HTMLInputElement).value; |
27 | | - value = newValue; |
28 | | - dispatch("change", { value: newValue }); |
29 | | - }; |
30 | | -
|
31 | | - text.inputEl.addEventListener("input", textChangeHandler); |
32 | 25 | }); |
33 | 26 |
|
34 | 27 | onDestroy(() => { |
35 | | - if (text?.inputEl && textChangeHandler) { |
36 | | - text.inputEl.removeEventListener("input", textChangeHandler); |
| 28 | + if (text?.inputEl && inputHandler) { |
| 29 | + text.inputEl.removeEventListener("input", inputHandler); |
37 | 30 | } |
38 | 31 | }); |
39 | 32 |
|
40 | 33 | $: if (text) { |
| 34 | + attachEventListeners(text); |
41 | 35 | updateTextComponentAttributes(text, value, disabled, placeholder, type, styles); |
42 | 36 | } |
43 | 37 |
|
| 38 | + function handleInput(event: Event) { |
| 39 | + const input = event.target as HTMLInputElement | null; |
| 40 | + const newValue = input?.value ?? ""; |
| 41 | +
|
| 42 | + value = newValue; |
| 43 | + dispatch("input", { value: newValue }); |
| 44 | + } |
| 45 | +
|
| 46 | + function handleChange(newValue: string) { |
| 47 | + value = newValue; |
| 48 | + dispatch("change", { value: newValue }); |
| 49 | + } |
| 50 | +
|
| 51 | + function attachEventListeners(component: TextComponent) { |
| 52 | + if (!component?.inputEl || inputHandler) return; |
| 53 | +
|
| 54 | + changeHandler = handleChange; |
| 55 | + component.onChange(changeHandler); |
| 56 | +
|
| 57 | + inputHandler = handleInput; |
| 58 | + component.inputEl.addEventListener("input", inputHandler); |
| 59 | + } |
| 60 | +
|
44 | 61 | function updateTextComponentAttributes( |
45 | 62 | component: TextComponent, |
46 | 63 | currentValue: string, |
|
0 commit comments