简体   繁体   中英

How do I update an individual component using aurelia store?

I'm using the aurelia-store plugin. I have this list, and it's generally rendering correctly, except enabled/disabled which is what I'm working on.

export interface State {
  readonly availableGames: AvailableGame[];
  readonly myGames: Game[];
}

export const initialState: State = {
  availableGames: [
    { name: 'Foo', added: false },
    { name: 'Bar', added: false },
  ],
  myGames: [],
};

AvailableGames.html

<template>
  <require from="./game-add-button.html"></require>
  <div class="game-list">
    <ul class="list-group">
      <li repeat.for="game of state.availableGames">
        <game-add-button game.bind="game" on-add.call="addGameToMyList(game)"></game-add-button>
      </li>
    </ul>
  </div>
</template>

AvailableGames

import { autoinject } from 'aurelia-framework';
import { connectTo, Store } from 'aurelia-store';
import { Event } from '../Event';
import { State } from '../State';
import AvailableGame from './AvailableGame';
import Game from './Game';

@connectTo()
@autoinject()
export default class AvailableGames {

  readonly state!: State;

  constructor(private store: Store<State>) {
    this.store.registerAction(Event.ADD_GAME_TO_MY_LIST, (state, game) => this.onAddNewState(state, game));
  }

  async addGameToMyList(availableGame: AvailableGame): Promise<void> {
    const { added, ...game } = availableGame;
    return await this.store.dispatch(Event.ADD_GAME_TO_MY_LIST, game);
  }

  private onAddNewState(state: State, game: Game): State {
    return {
      ...state,
      myGames: [...state.myGames, game]
    };
  }
}

game-add-button.html

<template bindable="game,onAdd" role="button">
  <button class="button ${game.added ? 'is-success' : ''}" click.trigger="onAdd(game)" disabled.bind="game.added">
    ${game.name}
  </button>
</template>

GameAddButton.ts

@customElement('game-add-button')
export default class GameAddButton {
  @bindable game!: AvailableGame;
  @bindable onAdd!: (game: AvailableGame) => void
}

everything seems to work, except when I click the button, the state update is not reflected in the UI. How do I change my code so that the buttons state is reflected?

I don't know what your intention with the myGames array was, which you're pushing the selected game to in your action. But in your AvailableGames.html you're still iterating on availableGames and haven't modified it in your new state to say added: true for the selected game.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM