Svelte: Parameter in function not updated in each loop

Created on 25 May 2019  路  1Comment  路  Source: sveltejs/svelte

I made a small example but in nutshell: After the click, the DOM render correctly, but each parameter in the function which was before the clicked element, shifted.
I used the latest svelte (3.4.2)

let playlist= [{
  id: 1,
  name: 'Foo'
}, {
  id: 2,
  name: 'Bar'
}, {
  id: 3,
  name: 'Boom'
}];

const removeSong = id => () => {
  playlist = playlist.filter(song => song.id !== id);
};
{#each playlist as song}
<h1 on:click={removeSong(song.id)}>{song.id}: {song.name}</h1>
{/each}

p.s.: It's fixing if I provide key expression
{#each playlist as song (song.id)}

Most helpful comment

Hi David, the problem is how you call the removeSong() function. the on:click gives a MouseEvent; if you want to bind your own event handler (in your case: the removeSong function) you must use an inline function that receives the original click event. In your inline function you can call whatever function you want.

However, using a keyed array (adding an id in the each loop) is probably a cleaner solution.

```

Called ID: {idParam}

{#each playlist as song}


{/each}

>All comments

Hi David, the problem is how you call the removeSong() function. the on:click gives a MouseEvent; if you want to bind your own event handler (in your case: the removeSong function) you must use an inline function that receives the original click event. In your inline function you can call whatever function you want.

However, using a keyed array (adding an id in the each loop) is probably a cleaner solution.

```

Called ID: {idParam}

{#each playlist as song}


{/each}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davidcallanan picture davidcallanan  路  3Comments

mmjmanders picture mmjmanders  路  3Comments

ricardobeat picture ricardobeat  路  3Comments

noypiscripter picture noypiscripter  路  3Comments

bestguy picture bestguy  路  3Comments