[Javascript] Data ownership, avoid accidently mutation
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] Data ownership, avoid accidently mutation相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
使用 javascript / jQuery 获取 data-* 属性列表
[Javascript] Avoiding Mutations in JavaScript with Immutable Data Structures