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:

  1. import {Component, Input, ViewEncapsulation, EventEmitter, Output} from 'angular2/core';
  2. @Component({
  3. selector: 'todo-item-renderer',
  4. // encapsulation:ViewEncapsulation.Emulated, //Default, (parent style pass )in and no (child style go) out
  5. // encapsulation:ViewEncapsulation.Native, // no in and no out
  6. encapsulation:ViewEncapsulation.None, // in and out
  7. template: `
  8. <style>
  9. .completed{
  10. text-decoration: line-through;
  11. }
  12. </style>
  13. <div>
  14. <span [ngClass]="todo.status"
  15. [contentEditable]="todo.isEdit">{{todo.title}}</span>
  16. <button (click)="toggleTodo.emit(todo)">Toggle</button>
  17. <button (click)="todo.edit()">Edit</button>
  18. </div>
  19. `
  20. })
  21.  
  22. export class TodoItemRenderer{
  23. @Input() todo;
  24. @Output() toggleTodo = new EventEmitter();
  25. }

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:

  1. import {Component} from 'angular2/core';
  2. import {TodoService} from './TodoService';
  3. import {TodoItemRenderer} from './TodoItemRenderer';
  4. import {StartedPipe} from './started-pipe';
  5.  
  6. @Component({
  7. selector: 'todo-list',
  8. pipes: [StartedPipe],
  9. directives: [TodoItemRenderer],
  10. template: `
  11. <ul>
  12. <li *ngFor="#todo of todoService.todos | started">
  13. <todo-item-renderer [todo]="todo"
  14. (toggleTodo) = "todoService.toggleTodo($event)" // Contains the todoModule
  15. ></todo-item-renderer>
  16. </li>
  17.  
  18. </ul>
  19. `
  20. })
  21.  
  22. export class TodoList{
  23. constructor(public todoService: TodoService){
  24.  
  25. }
  26. }

TodoService.ts:

  1. import {TodoModule} from './TodoModule';
  2. export class TodoService {
  3. todos = [
  4. //init some todos
  5. new TodoModule("eat"),
  6. new TodoModule("sleep"),
  7. new TodoModule("code")
  8. ];
  9.  
  10. addNewTodo(todo) {
  11. this.todos = [...this.todos, todo];
  12. }
  13.  
  14. toggleTodo(todo) {
  15.  
  16. const i = this.todos.indexOf(todo);
  17.  
  18. todo.toggle();
  19.  
  20. this.todos = [
  21. ...this.todos.slice(0, i),
  22. todo,
  23. ...this.todos.slice( i + 1)
  24. ];
  25. }
  26. }

---------------------

[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. mysql慢查优化总结

    1.优化sql语句结构 or改成union,使用start,limit 先只查询出所有的id,然后再排序.如果查询出所有的id仍然很慢,就要仔细考虑了. 2.添加索引 mysql每次查询只能使用一个索 ...

  2. RecyclerView更通用——listView的onItemClick,onLongItemClick,addHeaderView,addFooterView

    一.点击事件 setOnItemClickListener,setOnItemLongClickListener RecyclerView中虽然没有提供上面这两个接口,但是给我们提供了另外一个接口:O ...

  3. 几种常用的Java数据源解决方案

    http://blog.163.com/qqabc20082006@126/blog/static/22928525201041944847653/

  4. iOS 8 自动布局sizeclass和autolayout的基本使用

    1.首先创建新的工程,设置rootviewcontroller(这里不再多说) 2.勾选下面(因为我们到下面是使用sizeClass,所以勾选两个): 3.这里我创建了一个lable,名称为View1 ...

  5. 标准SQL语言的用法

    原文链接:http://www.ifyao.com/2015/05/18/%E6%A0%87%E5%87%86%E7%9A%84sql%E8%AF%AD%E8%A8%80%E4%BD%BF%E7%94 ...

  6. 输入框 input只能输入正数和小数点

    输入框 input只能输入正数和小数点  限制文本框只能输入正数,负数,小数 onkeyup="value=value.replace(/[^\-?\d.]/g,'')" 限制文本 ...

  7. php经典面试题

    1. 用PHP打印出前一天的时间,打印格式是2007年5月10日 22:21:21 2. PHP代码如下:$a="hello"; $b=&$a;unset($b);$b=& ...

  8. android EditText内嵌图片

    如下所示: 主要用到的属性:android:drawableLeft <EditText android:layout_width="match_parent" androi ...

  9. C# and android

    http://www.cnblogs.com/GoodHelper/archive/2011/07/08/android_socket_chart.html http://blog.csdn.net/ ...

  10. SSL 证书申请(居然还可以在淘宝上购买)

    免费的目前有 2 个国内的:免费SSL证书申请国外的:StartSSL™ Certificates & Public Key Infrastructure 备注:其实,国内的这家的根证书,也是 ...