AngularJS 2.0 From The Beginning - Immutable JS - Day Twenty Two

In this Angular 2.0 article series, we have already discussed about different basic concepts or features of AngularJs 2.0 like data binding, Directives, pipes, Service, route, http modules etc. Now, in this article, we will discuss about Immutable JS concept. In case you have not had a look at the previous articles of this series, go through the links mentioned below.

Immutable.js is a library, which provides immutable generic collections.

What is Immutability?

Immutability is a design pattern, where something can't be modified after being instantiated. If we want to change the value of that thing, we must recreate it with the new value instead. Some JavaScript types are immutable and some are mutable, which means their value can change without having to recreate it. Let's explain this difference with some examples.

  1. let movie = {  
  2.   name: 'Star Wars',  
  3.   episode: 7  
  4. };  
  5.   
  6. let myEp = movie.episode;  
  7.   
  8. movie.episode = 8;  
  9.   
  10. alert(myEp); // outputs 7 

As you can see in this case, although we changed the value of movie.episode, the value of myEp didn't change. That's because movie.episode's type, number, is immutable.

  1. let movie1 = {  
  2.   name: 'Star Wars',  
  3.   episode: 7  
  4. };  
  5.   
  6. let movie2 = movie1;  
  7.   
  8. movie2.episode = 8;  
  9.   
  10. alert(movie1.episode); // outputs 8 

In this case however, changing the value of an episode on one object has also changed the value of the other. It is because movie1 and movie2 are of the Object type and Objects are mutable. Of JavaScript built-in types, the following are immutable. 

  • Boolean
  • Number
  • String
  • Symbol
  • Null
  • Undefined

The following are mutable. 

  • Object
  • Array
  • Function

String is an unusual case, since it can be iterated over using for...of and provides numeric indexers just like an array, but doing something, as shown below. 

  1. let message = 'Hello world';  
  2. message[5] = '-';  
  3. alert(message); // writes Hello world   

The case for Immutability

One of the more difficult things to manage when structuring an Application is managing its state. This is especially true when your Application can execute code asynchronously. Let's say you execute some piece of code, but something causes it to wait (such as an HTTP request or a user input). After it's completed, you notice the state; it's expecting changed because some other piece of code executed asynchronously and changed its value.

Dealing with this kind of behavior on a small scale might be manageable, but this can show up all over an Application and can be a real headache as the Application gets bigger with more interactions and more complex logic. Immutability attempts to solve this by making sure that any object referenced in one part of the code can't be changed by another part of the code unless they have the ability to rebind it directly.

Object.assign

Object.assign allows us to merge one object's properties into another, replacing the values of the properties with the matching names. We can use this to copy an object's value without altering the existing one.

  1. let movie1 = {  
  2.   name: 'Star Wars',  
  3.   episode: 7  
  4. };  
  5.   
  6. let movie2 = Object.assign({}, movie1);  
  7.   
  8. movie2.episode = 8;  
  9.   
  10. alert(movie1.episode); // writes 7  
  11. alert(movie2.episode); // writes 8   

Object.freeze

Object.freeze allows us to disable object mutation.

  1. let movie1 = {  
  2.   name: 'Star Wars',  
  3.   episode: 7  
  4. };  
  5.   
  6. let movie2 = Object.freeze(Object.assign({}, movie1));  
  7.   
  8. movie2.episode = 8; // fails silently in non-strict mode,  
  9.                     // throws error in strict mode  
  10.   
  11. alert(movie1.episode); // writes 7  
  12. alert(movie2.episode); // writes 7   

Immutable.js Basics

To solve our mutability problem, Immutable.js must provide immutable versions of the two core mutable types i.e. Object and Array.

Immutable.Map

Map is the immutable version of JavaScript's object structure. Due to JavaScript objects having the concise object literal syntax, it's often used as a key-value store with the key being type string. This pattern closely follows the map data structure. Let's revisit the previous example, but use Immutable.Mapinstead.

Instead of binding the object literal directly to movie1, we pass it as an argument to Immutable.Map. This changes how we interact with movie1's properties. To get the value of a property, we call the get method, passing the property name; which we want, like how we'd use an object's string indexer. To set the value of a property, we call the set method, pass the property name and the new value. Note that it won't mutate the existing Map object - it returns a new object with the updated property, so we must rebind the movie2 variable to the new object.

  1. let movie1 = Immutable.Map<string, any>({  
  2.   name: 'Star Wars',  
  3.   episode: 7  
  4. }); 
Now, demonstrate this concept. Write down the code given below.

app.component.homepage.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2. import { Http, Response } from '@angular/http';  
  3. import * as Immutable from 'immutable';  
  4.   
  5. @Component({  
  6.     moduleId: module.id,  
  7.     selector: 'home-page',  
  8.     templateUrl: 'app.component.homepage.html'  
  9. })  
  10.   
  11. export class HomePageComponent implements OnInit {  
  12.   
  13.     private data: Array<any> = [];  
  14.   
  15.     constructor() {  
  16.     }  
  17.   
  18.     ngOnInit(): void {  
  19.     }  
  20.   
  21.     private fnShow(): void {  
  22.         let movie1 = Immutable.Map<string, any>({  
  23.             name: 'Star Wars',  
  24.             episode: 7  
  25.         });  
  26.   
  27.         let movie2 = movie1;  
  28.   
  29.         movie2movie2 = movie2.set('episode', 8);  
  30.   
  31.         alert(movie1.get('episode')); // writes 7  
  32.         alert(movie2.get('episode')); // writes 8  
  33.     }  
  34.   
  35.     private fnMerge(): void {  
  36.         let baseButton = Immutable.Map<string, any>({  
  37.             text: 'Click me!',  
  38.             state: 'inactive',  
  39.             width: 200,  
  40.             height: 30  
  41.         });  
  42.   
  43.         let submitButton = baseButton.merge({  
  44.             text: 'Submit',  
  45.             state: 'active'  
  46.         });  
  47.   
  48.         console.log(submitButton);  
  49.     }  

app.component.homepage.html
  1. <div>  
  2.     <h3>Immutable JS</h3>  
  3.     <input type="button" value="Show Data (Map)" (click)="fnShow()"/>  
  4.     <input type="button" value="Show Data (Merge)" (click)="fnMerge()" />  
  5. </div> 
app.module.ts
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { ReactiveFormsModule } from "@angular/forms";  
  4.   
  5. import { HomePageComponent } from './src/app.component.homepage';  
  6.   
  7. @NgModule({  
  8.     imports: [BrowserModule, ReactiveFormsModule],  
  9.     declarations: [HomePageComponent],  
  10.     bootstrap: [HomePageComponent]  
  11. })  
  12. export class AppModule { } 
main.ts
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2.   
  3. import { AppModule } from './app.module';  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule); 
index.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2 - Immutable JS </title>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <link href="../resources/style/bootstrap.css" rel="stylesheet" />  
  8.     <link href="../resources/style/style1.css" rel="stylesheet" />  
  9.     <!-- Polyfill(s) for older browsers -->  
  10.     <script src="../resources/js/jquery-2.1.1.js"></script>  
  11.     <script src="../resources/js/bootstrap.js"></script>  
  12.   
  13.     <script src="../node_modules/core-js/client/shim.min.js"></script>  
  14.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  15.     <script src="../node_modules/reflect-metadata/Reflect.js"></script>  
  16.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  17.     <script src="../systemjs.config.js"></script>  
  18.     <script>  
  19.         System.import('app').catch(function (err) { console.error(err); });  
  20.     </script>  
  21.     <!-- Set the base href, demo only! In your app: <base href="/"> -->  
  22.     <script>document.write('<base href="' + document.location + '" />');</script>  
  23. </head>  
  24. <body>  
  25.     <home-page>Loading</home-page>  
  26. </body>  
  27. </html> 
Now, run the code and output, as shown below.
 


Similar Articles