Fro*_*yon 15 javascript typescript ecmascript-6 immutable.js angular
说我有课Task和TaskGroup
class Task{
constructor(public text:string){}
}
class TaskGroup {
constructor(public title:string = "new task group", public tasks:Task[] = []){}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的Angular 2服务中,我将创建一个不可变的TaskGroups列表
@Injectable()
class TaskService {
taskGroups:Immutable.List<TaskGroup>;
constructor() {
this.taskGroups = Immutable.List<TaskGroup>([new TaskGroup("Coding tasks")]);
}
}
Run Code Online (Sandbox Code Playgroud)
这样只有taskGroups List是不可变的.不管里面是什么都不是.即使我Immutable.fromJS(...)而不是Immutable.List<Board>(...)嵌套对象都是普通的'Javascript对象.
不可变的JS不会假定类继承(使用ES6#562继承自Immutable对象)
//can't do this!
class TaskGroup extends Immutable.Map<string, any>{
constructor(public title:string = "new task group", public tasks:Task[]){}
}
//it complained about the class not having methods like set, delete etc
Run Code Online (Sandbox Code Playgroud)
那么如何创建Immutable类对象呢?
你可以这样做:
const TodoRecord = Immutable.Record({
id: 0,
description: "",
completed: false
});
class Todo extends TodoRecord {
id:number;
description:string;
completed: boolean;
constructor(props) {
super(props);
}
}
let todo:Todo = new Todo({id: 1, description: "I'm Type Safe!"});
Run Code Online (Sandbox Code Playgroud)
不完美但工作.
它来自这篇伟大的博客文章:https: //blog.angular-university.io/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/
| 归档时间: |
|
| 查看次数: |
7225 次 |
| 最近记录: |