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的更多相关文章

  1. [Immutable + AngularJS] Use Immutable .List() for Angular array

    const stores = Immutable.List([ { name: 'Store42', position: { latitude: 61.45, longitude: 23.11, }, ...

  2. [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 ...

  3. [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 ...

  4. Angular 1 深度解析:脏数据检查与 angular 性能优化

    TL;DR 脏检查是一种模型到视图的数据映射机制,由 $apply 或 $digest 触发. 脏检查的范围是整个页面,不受区域或组件划分影响 使用尽量简单的绑定表达式提升脏检查执行速度 尽量减少页面 ...

  5. [Javascript] Avoiding Mutations in JavaScript with Immutable Data Structures

    To demonstrate the difference between mutability and immutability, imagine taking a drink from a gla ...

  6. [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 ...

  7. 使用 Immutable Subject 来驱动 Angular 应用

    现状 最近在重构手上的一个 Angular 项目,之前是用的自己写的一个仿 Elm 架构的库来进行的状态管理,期间遇到了这些痛点: 样板代码太多 异步处理太过繁琐 需要单独维护一个 npm 包 其中, ...

  8. [Immutable.js] Transforming Immutable Data with Reduce

    Immutable.js iterables offer the reduce() method, a powerful and often misunderstood functional oper ...

  9. [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 ...

随机推荐

  1. oracle、db2、sybase大型数据库面试总结

    1. oracle数据库单例.多例模式. 数据库创建之后会有一系列为该数据库提供服务的内存空间和后台进程,称为该数据库的实例. 每一个数据库至少会有一个实例为其服务. 2. mysql获取字段的长度用 ...

  2. 向ASP.NET服务器控件中嵌入CSS资源

    Step1:于[项目解决方案]中右键新建[ASP.NET服务器控件]项目 Step2:于项目中添加[Resources]文件夹,于该文件夹下添加[CSS文件] Step3:单击该CSS文件,并将[属性 ...

  3. (转)ASP.NET里面简单的记住用户名和密码

    using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using S ...

  4. PHP语言中使用JSON

    原文地址:http://www.ruanyifeng.com/blog/2011/01/json_in_php.html 在PHP语言中使用JSON 目前,JSON已经成为最流行的数据交换格式之一,各 ...

  5. Linux系统文本命令快速登录与退出

    Linux是一个多用户的操作系统,用户要使用该系统,首先必须登录系统,使用完系统后,必须退出系统.用户登录系统时,为了使系统能够识别自己,必须输入用户名和密码,经系统验证无误后方能进入系统.在系统安装 ...

  6. Java下载Servlet Demo

    request.setCharacterEncoding("utf-8"); String name=request.getParameter("name"); ...

  7. python 装饰器简介

    24.装饰器     1.@ + 函数名:#1自动执行outer函数并且将下面的函数名f1当做参数传递                   #2将outer函数的返回值,重新赋值给f1. def ou ...

  8. twsited(4)--不同模块用redis共享以及用web发送数据到tcpserver

    上一章开头我们说,要连接之前flask系列文章中的用户,结果篇幅不够,没有实现. 今天我们把它实现一下.话说,不同模块之间,该如何联系在一起,通常都是mysql.redis.rabbitmq还有RPC ...

  9. WebStorm 的使用(一)

    WebStorm是一个捷克公司开发的,功能虽然很强大,但UI貌似一直不是东欧人的强项.WebStorm默认的编辑器颜色搭配不算讲究,我看习惯了VS2012的Dark Theme,再看这个顿觉由奢入俭难 ...

  10. Linux_install mod_ssl openssl apache

    1.下载 mod_ssl 和 apache 登入http://www.modssl.org/source/,下载 mod_ssl-2.8.31-1.3.41.targz: 2.8.31是mod_ssl ...