svelte icon indicating copy to clipboard operation
svelte copied to clipboard

Update `bind:group` when the binded `input` is removed

Open hyunbinseo opened this issue 1 year ago • 4 comments

Describe the problem

bind:group can be out of sync with the DOM when the binded input elements are removed.

<script lang="ts">
  let selectedItems = ['a', 'b', 'c'];
  let items = ['a', 'b', 'c'];
  $: console.log(selectedItems);
</script>

<!-- This does not update the selectedItems array. -->
<!-- Expected: selectedItems becomes [] and is logged. -->
<button type="button" on:click={() => (items = [])}>Remove all items</button>

{#each items as item (item)}
  <label>
    <input type="checkbox" value={item} bind:group={selectedItems} />
    <span>{item}</span>
  </label>
{/each}

https://svelte.dev/repl/96dcce0d2426459c9a08c0fdc105a246?version=4.2.19

Describe the proposed solution

Update bind:group array when the binded input elements are removed

Importance

nice to have

hyunbinseo avatar Aug 24 '24 09:08 hyunbinseo

I will look into this soon :)

etainad008 avatar Sep 03 '24 15:09 etainad008

At first I wondered if this is unwanted behavior. In the logical sense, if you no longer have any elements - the group array is just like any good old array - it is not bound to anything anymore. But then I looked into another case. I made the button pop an element from the items array. In this case, we are left with a and b checkboxes, but not c. The group array should only contain a and b at this point, but it is indeed not updated, and still contains c. This convinced me that the former is unwanted behavior (?). Would like thoughts about the matter - this seems like a fundamental change in bind:group.

etainad008 avatar Sep 03 '24 15:09 etainad008

Then you need to cover the case when you start with

  let selectedItems = ['a', 'd'];
  let items = ['a', 'b', 'c'];

where d is selected, but it is not an available option, which will cause the array to be updated just by displaying it, which is bad behaviour.

It's uncommon for the list of options to be dynamic during selection. If your case does so, it's not that hard to remove the deleted option from the selected ones. In other cases, you may want new options to be selected by default.

7nik avatar Sep 03 '24 18:09 7nik

True. It is bad if bind:group will act this way.

etainad008 avatar Sep 03 '24 19:09 etainad008