Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

model パターン #7

Closed
baronTommy opened this issue Feb 25, 2020 · 0 comments
Closed

model パターン #7

baronTommy opened this issue Feb 25, 2020 · 0 comments

Comments

@baronTommy
Copy link
Owner

baronTommy commented Feb 25, 2020

https://blog.yuhiisk.com/archive/2017/07/10/frontend-spa-with-model.html

const postsState = new PostsModel();

function reducer(state = postsState, action) {
  switch (action.type) {
    // データの追加
    case ActionTypes.GET_POSTS:
      return state.add(action.posts);

    // データの削除
    case ActionTypes.REMOVE_POST:
      return state.remove(action.index);

    // データの更新
    case ActionTypes.UPDATE_POST:
      return state.update(action.data);

    // チェックボックスのトグル
    case ActionTypes.TOGGLE_CHECK:
      return state.toggleCheck(action.id);

    default:
      return state;
  }
}
import { Record } from 'immutable';

const PostsRecord = Record({
  posts: [], // 取得データ
});

class Posts extends PostsRecord {

  /**
   * データの追加
   * @param {array} data - 取得したデータ配列
   */
  add(data) {
    return this.set('entries', this.get('posts').concat(data));
  }

  /**
   * データの削除
   * @param {number} id - postのid
   */
  remove(id) {
    const _posts = this.get('posts').filter((post) => post.id !== id);
    return this.set('posts', _posts);
  }

  /**
   * データの更新
   * @param {object} data - postオブジェクト
   */
  update(data) {
    const _posts = this.get('posts').map((post) => {
      if (post.id === data.id) {
        return data;
      }
      return post;
    });
    return this.set('posts', _posts);
  }

  /**
   * チェックのトグル
   * @param {number} id - postのid
   */
  toggleCheck(id) {
    const _posts = this.get('posts').map((post) => {
      if (post.id === id) {
        post.checked = !post.checked;
      }
      return post;
    });
    return this.set('posts', _posts);
  }

}

export default Posts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant