Events and local state

@click={ pick(g) } calls the view's pick handler with the chip's genre when it is clicked. Handlers live in the view's events, written as arrow functions so this is the view. Any DOM event works the same way (@input, @submit, @keydown:enter), and inside a handler's arguments event is the DOM event.

State that only this view cares about, like which genre is picked, is local state:

  • this.setData('genre', g) stores a value and re-renders.
  • this.getData() reads the view's current data, local state included.
  • this.refresh() runs data() again.

setData() alone does not run data(). When data() derives something from the local value, such as the filtered list, call refresh() after it, and have data() read the value back with getData():

data(params, props) {
  const genre = this.getData().genre ?? 'All';
  const all = this.ctx.store.findMany('album');
  return {
    genre,
    genres: ['All', ...new Set(all.map((album) => album.genre))],
    albums: genre === 'All' ? all : all.filter((album) => album.genre === genre),
  };
}

Your turn

  1. Fill in pick: store the genre with setData, then refresh().
  2. Update data() to read the genre back and filter the albums, as above.
  3. Mark the chosen chip: add {#if g === genre}is-on{/if} to its class, and aria-pressed="{ g === genre }".

Local state belongs to one view and is gone when it leaves the page. Anything other views need, like the playlist, belongs in the store.

Chapters