[Javascript] Data ownership, avoid accidently mutation

只谈情不闲聊 提交于 2020-04-05 17:53:04

When implementing the store partten, we need to be careful about mutation.

class DataStore {
  private lessons: Lesson[] = [];

  private lessonsSubject = new SubjectImplementation();

  lessonsLists$: Observable = {
    subscribe(obs) {
      this.lessonsSubject.subscribe(obs);
      obs.next(lessons);
    },
    unsubscribe(obs) {
      this.lessonsSubject.unsubscribe(obs);
    },
  };

  initializeLessonsList(newList: Lesson[]) {
    this.lessons = _.cloneDeep(newList);
    this.lessonsSubject.next(lessons);
  }

  addLessons(newLessons) {
    this.lessons.push(_.cloneDeep(newLessons)); // make a deep clone
    this.lessonsSubject.next(this.lessons);
  }
}

export const store = new DataStore();

We need to make a deep clone in order to avoid accidently mutation.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!