码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Data ownership, avoid accidently mutation

时间:2020-04-05 09:14:09      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:about   init   lists   slist   exp   ons   datastore   export   col   

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.

[Javascript] Data ownership, avoid accidently mutation

标签:about   init   lists   slist   exp   ons   datastore   export   col   

原文地址:https://www.cnblogs.com/Answer1215/p/12635608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!