[Angular 2] Refactoring mutations to enforce immutable data in Angular 2
When a Todo property updates, you still must create a new Array of Todos and assign a new reference. This lesson walks you through refactoring from the current approach to the immutable approach.
TodoItemRender.ts:
import {Component, Input, ViewEncapsulation, EventEmitter, Output} from 'angular2/core';
@Component({
selector: 'todo-item-renderer',
// encapsulation:ViewEncapsulation.Emulated, //Default, (parent style pass )in and no (child style go) out
// encapsulation:ViewEncapsulation.Native, // no in and no out
encapsulation:ViewEncapsulation.None, // in and out
template: `
<style>
.completed{
text-decoration: line-through;
}
</style>
<div>
<span [ngClass]="todo.status"
[contentEditable]="todo.isEdit">{{todo.title}}</span>
<button (click)="toggleTodo.emit(todo)">Toggle</button>
<button (click)="todo.edit()">Edit</button>
</div>
`
})
export class TodoItemRenderer{
@Input() todo;
@Output() toggleTodo = new EventEmitter();
}
Here we use EventEmitter to emit a event called 'toggleTodo'. Parent component (TodoList.ts) will catch the event and update the TodoService's todos array.
And todos array should be a new reference.
TodoList.ts:
import {Component} from 'angular2/core';
import {TodoService} from './TodoService';
import {TodoItemRenderer} from './TodoItemRenderer';
import {StartedPipe} from './started-pipe';
@Component({
selector: 'todo-list',
pipes: [StartedPipe],
directives: [TodoItemRenderer],
template: `
<ul>
<li *ngFor="#todo of todoService.todos | started">
<todo-item-renderer [todo]="todo"
(toggleTodo) = "todoService.toggleTodo($event)" // Contains the todoModule
></todo-item-renderer>
</li>
</ul>
`
})
export class TodoList{
constructor(public todoService: TodoService){
}
}
TodoService.ts:
import {TodoModule} from './TodoModule';
export class TodoService {
todos = [
//init some todos
new TodoModule("eat"),
new TodoModule("sleep"),
new TodoModule("code")
];
addNewTodo(todo) {
this.todos = [...this.todos, todo];
}
toggleTodo(todo) {
const i = this.todos.indexOf(todo);
todo.toggle();
this.todos = [
...this.todos.slice(0, i),
todo,
...this.todos.slice( i + 1)
];
}
}
---------------------
[Angular 2] Refactoring mutations to enforce immutable data in Angular 2的更多相关文章
- [Immutable + AngularJS] Use Immutable .List() for Angular array
const stores = Immutable.List([ { name: 'Store42', position: { latitude: 61.45, longitude: 23.11, }, ...
- [Javascript] Simplify Creating Immutable Data Trees With Immer
Immer is a tiny library that makes it possible to work with immutable data in JavaScript in a much m ...
- [Angular2 Router] Resolving route data in Angular 2
From Article: RESOLVING ROUTE DATA IN ANGULAR 2 Github If you know Anuglar UI router, you must know ...
- Angular 1 深度解析:脏数据检查与 angular 性能优化
TL;DR 脏检查是一种模型到视图的数据映射机制,由 $apply 或 $digest 触发. 脏检查的范围是整个页面,不受区域或组件划分影响 使用尽量简单的绑定表达式提升脏检查执行速度 尽量减少页面 ...
- [Javascript] Avoiding Mutations in JavaScript with Immutable Data Structures
To demonstrate the difference between mutability and immutability, imagine taking a drink from a gla ...
- [Angular 2] implements OnInit, OnDestory for fetching data from server
Link: https://angular.io/docs/js/latest/api/core/OnInit-interface.html, https://www.youtube.com/watc ...
- 使用 Immutable Subject 来驱动 Angular 应用
现状 最近在重构手上的一个 Angular 项目,之前是用的自己写的一个仿 Elm 架构的库来进行的状态管理,期间遇到了这些痛点: 样板代码太多 异步处理太过繁琐 需要单独维护一个 npm 包 其中, ...
- [Immutable.js] Transforming Immutable Data with Reduce
Immutable.js iterables offer the reduce() method, a powerful and often misunderstood functional oper ...
- [Immutable.js] Using fromJS() to Convert Plain JavaScript Objects into Immutable Data
Immutable.js offers the fromJS() method to build immutable structures from objects and array. Object ...
随机推荐
- java里面List和Array的区别是什么?
java里面的List和Array的区别是什么? 1:数组是定长,list是自动增长.2:数组效率高,list效率低.总结:数组牺牲功能增加效率,list牺牲效率增加功能. http://bbs.cs ...
- android SQLite使用SQLiteOpenHelper类对数据库进行增删查改
一个简单的例子,当点击按钮时进行相应的操作,效果图如下: 项目代码如下: DatabaseHelper类 package com.example.sqlitedatebasetest; import ...
- ORA-16018: cannot use LOG_ARCHIVE_DEST with LOG_ARCHIVE_DEST_n or DB_RECOVERY_FILE_DEST【error收集】
之前一直没有注意一个事情, 关于设置archive归档路径设置的问题. 设置数据库为归档模式的命令: 1.首先要切换到mount状态: 2.执行alter system archivelog; 3.查 ...
- ios视图切换之push与present混用
在变成过程中,经常遇到两个视图控制器之间的切换,导航控制器即UINaVigation是最常用的一种,有时为了某些效果又需要进行模态切换,即present. 我们的布局经常是在window上加一个nav ...
- DEV XtraGrid绑定非绑定列(转)
在Gridview创建一列 .将该列的UnboundType属性设置为bound(默认值)以外的数据类型 为该列设置一个窗体内全局唯一的FieldName,注意这个FieldName甚至不能出现在 ...
- JS滚动条下拉事件
<script type="text/javascript"> window.onscroll = function(){ var t = document.docum ...
- xml约束之schema
使用名称空间引入Schema : 通常需要在Xml文档中的根结点中使用schemaLocation属性来指定. <itcast:书架 xmlns:itcast="http://www. ...
- MongoDB insert/update/one2many案例
以博文与评论为例,博文有标题内容,对应多个评论,评论有评论人.评论内容等. ()插入一条博文: db.blog.insert( {','title':'this is blog title1','co ...
- hdu 2079 选课时间(题目已修改,注意读题)
http://acm.hdu.edu.cn/showproblem.php?pid=2079 背包 #include <cstdio> #include <cstring> # ...
- drawBitmapMesh方法关键参数的说明
bitmap:指定需要扭曲的源位图.meshWidth:该参数控制在横向上把该源位图划分成多少格.meshHeight:该参数控制在纵向上把该源位图划分成多少格.verts:该参数是一个长度为(mes ...