<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SungTheCoder on Medium]]></title>
        <description><![CDATA[Stories by SungTheCoder on Medium]]></description>
        <link>https://medium.com/@sungyeol.choi?source=rss-e7fcc9d942f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N9W96UmQm0qZJ2MZWnkoxw.jpeg</url>
            <title>Stories by SungTheCoder on Medium</title>
            <link>https://medium.com/@sungyeol.choi?source=rss-e7fcc9d942f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:49:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sungyeol.choi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a scalable web server on AWS]]></title>
            <link>https://medium.com/sungthecoder/building-a-scalable-web-server-on-aws-44ba4bbfc00d?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/44ba4bbfc00d</guid>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Sun, 21 May 2017 22:02:26 GMT</pubDate>
            <atom:updated>2017-12-07T00:02:45.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_hx4BxGZ9qYODhnTn-Bjg.jpeg" /></figure><p>In this post, we are going to talk about AWS. There are many AWS examples to create a simple web server with EC2. But a simple web server with a database in the same EC2 instance is not very scalable. Since web server and a database server is in the same virtual machine, it is hard to add another web server to scale out. In this post, I am going to walk through how I created an infrastructure for a web application (moodle) I installed in AWS.</p><h3>Virtual Private Cloud(VPC)</h3><p>Many of AWS resources depends on VPC. So let’s start with VPC.</p><p>If you use your computer at your home or office, the chances are that your IP address starts with 192.168.0.* or 10.0.0.1, which is different from your <a href="http://www.whatismypublicip.com/">public IP address</a>. That is because you are within your private network. Since your computer is in private network, outside world cannot initiate a connection to your machine. Try to create a web server on your laptop; you will be able to reach your web server within your home or office. But once you leave outside of your place, you won’t be able to reach your web server unless you make some unique configuration to your router.</p><p>AWS VPC is like your home or office network behind the router (or firewall). The AWS resources defined within the VPC does not have visibility to outside world unless you define a rule for outside exposure. And you have total control of what IP address ranges for these resources. And you can set inbound traffic rules to any of these resources. In this example, we want to provision database server and file server that are accessible from a web server, but not from outside of this private network. So it makes perfect sense to provision these resources within the VPC.</p><p>However, having a private network in the cloud that does not accept any inbound traffic would not be very useful. You can’t ssh into it; you can’t serve web pages from it; it sure is very secure, but not useful. So we are going to create a VPC with private and public subnets, where the resources in the private subnets are only available to other resources within the VPC and the ones in the public subnets are open to the internet.</p><h4>Creating VPC</h4><p>First, you will have to log in to AWS console. For the security reason, it is recommended to create an IAM user with admin privilege and log in with your IAM user. But that is out of the scope in this article so I will discuss this topic in another post.</p><p>Click VPC menu under “Networking &amp; Content Delivery” category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*jeo-u1DTwzYyPclA.png" /></figure><p>Before we build VPC, we will need a public IP address that can be attached to the VPC.</p><p>Click <strong>Elastic IP</strong> from the left side panel. And click blue <strong>Allocate new address</strong> button. And select “VPC” for the scope and click <strong>Allocate</strong>. We are going to use this address later when we create a VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dDYTkD05qykpbq_J.png" /></figure><p>Now go back to VPC dashboard and click the big blue “Start VPC Wizard” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N1_IIKNkD2sxjMTN.png" /></figure><p>Open “VPC with public and private Subnets” tab on the left and click “Select” button. Name your VPC and rename public and private subnet name to suit your need. Allocate Elastic IP you just created and click “Create VPC” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p3DiYaKPIjtmGEbn.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uIOJnZ3Bg4GiD3a3.png" /></figure><p>Congratulations! Your VPC is successfully created!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UyrJ2pExmKXScsVY.png" /></figure><h4>Security Group</h4><p>A security group is a firewall policy that you can apply to instances in your AWS environment. With the security group, you can allow inbound and outbound traffics from/to the AWS instances. Since we are going to have a web server, which accepts traffics from the public facing internet, and DB server and file server that accepts traffic from the web server, we need to create two security groups. And let’s call them public security group and private security group.</p><h4>Default Security Group</h4><p>Click <strong>Security Group</strong> on the left side navigation menu. You will find that there is already one security group created. This default security group is created when you created a VPC in the previous step. Select the default security group and open <strong>Inbound Rules</strong> tab at the bottom. You can see that this security group allows all inbound traffic from the instances with the same security group. I personally like to leave this default security group untouched and create my own security group for my own purpose. So let’s create some.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wLVZludSeZYguRRP.png" /></figure><h4>Public Security Group</h4><p>Click big blue <strong>Create Security Group</strong> button on the top and fill the name and description field in the modal window. And select the VPC you just created in the previous section from the drop down menu. Click <strong>Yes, Create</strong> button to create a security group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y8eIfNSWs3UgARDG.png" /></figure><p>Once it is created, select the security group and open <strong>Inbound Rules</strong> from the bottom pane. Click <strong>Edit</strong> button and add the following rules.</p><p>TypeSourceHTTP(80)0.0.0.0/0HTTPS(442)0.0.0.0/0SSH(22)0.0.0.0/0<br>This rule allows incoming traffic from any device out there with HTTP, HTTPS or SSH protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4t7-O9qVDQNsGTjc.png" /></figure><p>Click <strong>Save</strong> button and you will have public security group.</p><h4>Private Security Group</h4><p>Click <strong>Create Security Group</strong> button again to create another security group. Once the modal window opens, fill in the name and description field and select the VPC you just created. Click Yes, Create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6XPf1MRTgwBrt3We.png" /></figure><p>Just like the previous step, open <strong>Inbound Rules</strong> from the bottom pane. Click <strong>Edit</strong> and add the following rules.</p><p>TypeSourceNFS(2049)Public Security GroupMySQL/Aurora(3306)Public Security Group<br>We would like DB and file servers only accessible from the web server, which belongs to Public Security Group. So we set the inbound rules that accept NFS and MySQL services from instances with Public Security Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D2VtzEd-hnevt5ls.png" /></figure><p>If you want to be more strict, you can create two security groups with one accepts inbound traffic for NFS and another for MySQL. But for this simple setup, I will just keep it to one group.</p><h4>Subnets</h4><p>When we created a VPC in the previous section, we’ve created two subnets: one for public and another for private. But for some AWS services, such as EFS, requires two subnets from different availability zones(AZ). Different availability zones mean different data center, which has separate power, water supply, and network. Having multiple instances across multiple availability zones will protect the service from unexpected failure of any of the datacenter.</p><p>So let’s create another private subnet.</p><p>Click <strong>subnet</strong> from the left side navigation menu. And you will see two subnets from the list: Public and Private. Since we are going to create another private subnet, let’s rename current private subnet to ‘Private Subnet 1’, so we can create a new one to ‘Private Subnet 2’. Note the availability zone of the private subnet from the bottom pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nRrU7esFZh_CxhU5.png" /></figure><p>Now click big blue Create Subnet button on top. Once modal windows open, fill in the form with following values:</p><p>Name TagPrivate 2You can name anythingVPCTutorialChose the VPC you created in the previous stepAvailability Zoneus-east-1aChose AZ that is different from another subnetIPv4 CIDR block10.0.2.0/24Ip addresses on this subnet will starts from 10.0.2.1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1c4yMUto-GIGFaIR.png" /></figure><p>And then click <strong>Yes, Create</strong> button. Now you have two private subnets across two different AZ within your VPC.</p><h3>EC2 Instance</h3><p>What we’ve done so far is building a room, running wires (VPC) and connecting the wires to a few routers (Subnets.) It is time to create a server and connect it to the system.</p><p>For the web server, we are going to create an EC2 instance. Let’s go back to main page of the AWS console. Type <strong><em>EC2</em></strong> in the search box or click <strong>EC2</strong> under <strong>Compute</strong> section.</p><p>Click <strong>Launch Instance</strong> button on the page. On step1, Choose your favorite OS. In this example, we will use Amazon Linux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0A6l6RQbwAgUeND1.png" /></figure><p>On step2, you can choose the instance type. As you scroll down the menu, it gets more powerful and more expensive. Since we are just getting started and not expecting much traffic or computer usage, let’s choose t2.micro. Click <strong>Next: Configure Instance Details</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lJntGg1Oqd4iL9l_.png" /></figure><p>On Step 3: Configure Instance Details, fill up the form with following data</p><p>Number of instances1You can create multiple instances at once, but let’s have only one for nowPurchasing optionSpot instance can be cheaper if you can tolerateNetworkTutorial VPCSelect the VPC we created earlierSubnetPublic SubnetSelect the Public SubnetAuto-assign Public IPEnableThis web server needs a public IP address, so we can connect.IAM roleNoneLet’s not worry about it now.Shutdown behaviorStopIf you terminate, you will lose all the data written in the system.Enable termination protectioncheckProtect us from accidental termination and lose of data.MonitoringI turned it off because of additional charge. We will need it in the future, but not for the tutorial.TenancySharedLower cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h8PPBg5ex8XOdOan.png" /></figure><p>Once you fill up the form, click <strong>Next: Add Storage</strong>.</p><p>On Step4: Add Storage, you can add storage devices to your server. By default, you will have 8GB of General Purpose SSD with the selected OS installed, but you can add additional disk. Let’s have one more disk. <strong>Click Add New Volume</strong>. As you see on the screen, you can get up to 30GB of EBS for free. Since you already have 8GB of root volume, we will add an additional disk of 22GB. I checked the box for encryption for this additional device. This disk is /dev/sdb. Remember this, as we will need this name later to use the device. Let’s move on to the next step to add tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jELSSYx52xIXj25H.png" /></figure><p>On Step5, you can add tags to the instances and disk volumes you just created. It is always a good idea to name the things you created on AWS. So I add a name tag.</p><p>keyvaluenameTutorial Web Server<br>Click Nets: Configure Security Group</p><p>In the previous section, we have created a couple security groups: one public security group for the web server and private security group for database and file servers. We are going to apply the public security group to this EC2 instance. Click on Select an existing security group radio box and choose the Public security group you’ve created. The web server will accept the HTTP, HTTPS and SSH connection from the public internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BNxZ4kITAq3r-HWx.png" /></figure><p>Click <strong>Review and Launch button</strong> to review your configuration. You may see the warning message saying the security group is open to the world. That is what we expected and wanted. So let’s move on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CKV1iS2HAjAiUguI.png" /></figure><p>Click Launch button and create a key pair. After you download this .pem file, keep is a safe place. When you ssh to this machine, you will not need to enter a password. Instead, you will need to use this .pem file. That means, if you lose this file, you will be permanently locked out of the machine. And if you let other users on your computer access this file, anyone can login to the instance you just created. So make sure that only you have the read permission to the file by changing file mode to 400.</p><pre>$ chmod 400 TutorialKeyPair.pem</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fZ2XLt8rKb-9xEYd.png" /></figure><p>Click <strong>Launch instance</strong> button and it will start creating your EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ecktt7hC84_WpHR4.png" /></figure><p>Once the instance is initialized, you can connect to this instance. You can find the connection instruction by right clicking on the instance on the list and click on <strong>connect</strong> in the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nQKEmQrWMFMvpOXn.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NcNPdtVEc5aokCVG.png" /></figure><pre>$ ssh -i TutorialKeyPair.pem ec2-user@ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com</pre><pre>__|  __|_  )<br>       _|  (     /   Amazon Linux AMI<br>      ___|\___|___|</pre><pre><a href="https://aws.amazon.com/amazon-linux-ami/2017.03-release-notes/">https://aws.amazon.com/amazon-linux-ami/2017.03-release-notes/</a><br>6 package(s) needed for security, out of 6 available<br>Run &quot;sudo yum update&quot; to apply all updates.<br>[ec2-user@ip-10-0-0-228 ~]$</pre><p>Now you have your virtual machine, where you can install any web applications. Next, let&#39;s create a separate database server.</p><h3>Database Server</h3><p>Technically, you can install a database server on the same EC2 instance you&#39;ve just created in the previous step. Then you will have a web server and database server on the same machine. This configuration will work well for development or very small traffic website. But if you think there is a chance that the site traffic will increase in the future, it is better to pay a small price now to make it more future proof: separating database server is one of them. Then you can add a load balancer with increased number of EC2 web servers by cloning existing EC2 instance without worrying about duplicated database.</p><p>And you may also want to create another instance of EC2 to install a dedicated database server. However, AWS provide Relational Database Service, where amazon takes care of most of the database administration tasks. Let&#39;s create a database service for our web application to use.</p><p>In AWS console screen, click RDS under Database menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*ux2WYVRtj7bS8SVY.png" /></figure><p>While we are creating RDS instances, we are going to need subnet groups for the database instances. The subnet group is a collection of subnets that you create in a VPC. To increase the reliability of the database service, you can have AWS create multiple instances of database servers across multiple subnets. So we will have to tell AWS what are the subnets you&#39;d like database servers to reside. These subnets are typically private subnets and span across different availability zones.</p><p>To create a subnet group, click <strong>Subnet Group</strong> from the left side navigation menu and click <strong>Create DB Subnet Group</strong> button on top. Fill in the name and description field and select the Tutorial VPC for the VPC ID. Under this VPC, we have created three subnets: one public and two privates. We are adding these two private subnets and click <strong>Create</strong> button at the bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*exhPKPAV3sizk6VG.png" /></figure><p>Now we are ready to create a Database instance. Click <strong>Instances</strong> from the left side navigation menu. Click big blue <strong>Launch a DB Instance</strong> button. AWS provide multiple databases engines to choose from. In this example, we will go with MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lu1Ew8nTEd4BN06C.png" /></figure><p>Choose DB Engine Version that is supported by your web application. Some applications require a certain version of MySQL. But in this example, we are going with the default version. And you can choose the DB Instance Class and storage type and size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B_DcCGZncn7dVl6Q.png" /></figure><p>Name your instance on DB Instance Identifier and create a root username and password at Settings section. Click <strong>Next Step</strong> to configure Advanced Settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SWbqJ_55y0JC6CuG.png" /></figure><p>For Network &amp; Security section, select Tutorial VPC and tutorial DB subnet group we&#39;ve just created. And we don&#39;t want the database server accessible from outside world, select No for Publicly Accessible. And make sure to have Tutorial Private Security Group for VPC Security Group. I just left default values for Database Options and Backup sections. And Click <strong>Launch DB instance</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7tTT7QA44tLrGA-f.png" /></figure><p>Now you have a MySQL database server, let&#39;s try to connect to the database. Remember, the database server is in the private subnet, and the security group does allow traffics from instances with the public security group. So we cannot directly connect to the database from your laptop. We will have to ssh into the EC2 instance we&#39;ve created earlier.</p><p>First, let&#39;s find the database endpoint URL. Go to the RDS instances list, then you will see the database we&#39;ve just created in the list. Click on the row and you will see the database endpoint URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m7e9cYP43EsnkIsm.png" /></figure><p>Then, ssh into the EC2 instance. You may need to install MySQL client to connect to the MySQL server.</p><pre>$ ssh -i TutorialKeyPair.pem ec2-user@ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com</pre><pre>__|  __|_  )<br>       _|  (     /   Amazon Linux AMI<br>      ___|\___|___|</pre><pre>$ sudo yum install mysql<br>$ mysql -u tutorialroot -p -h xxx.yyy.zzz.rds.amazonaws.com<br>Enter password:</pre><pre>Welcome to the MySQL monitor. Commands end with ; or \g.<br>Your MySQL connection id is 34<br>Server version: 5.6.27-log MySQL Community Server (GPL)</pre><pre>Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.</pre><pre>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.</pre><pre>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.</pre><pre>mysql&gt;</pre><p>Woohoo! We now have a web server and a database server connected.</p><h3>Elastic File System(EFS)</h3><p>If your application requires a web server and database server, you don&#39;t need to follow this section and next. But many web application requires file storage for users to upload files. S3 is one of the solutions. But in this tutorial, we are going to use Elastic File System. With EFS, you can mount the EFS as network file system and shared among multiple web servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*lT9Rk16QH8GVxwAE.png" /></figure><p>To create a Filesystem, click <strong>EFS</strong> under Storage section and click <strong>Create file system</strong> big blue button.</p><p>In Step 1, select VPC and choose two private subnets for mount targets. And make sure that the security group for the mount targets is the private security group we created earlier. Click <strong>Next Step</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R6-xYS9Pvy4V4yYK.png" /></figure><p>In Step 2, add tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPb1UX67ssG27rfe.png" /></figure><p>In Step 3, review and create a file system by clicking <strong>Create File System</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GoOpgM2t_MABv039.png" /></figure><p>That was simple! Now we have a file system, how we use it? We need to mount the file system to read/write the files. You can find the mount instruction by opening the <strong>Amazon EC2 mount instructions</strong> link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EdDWMKRufEjyMnvi.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*4gnZT9b28mF3j4Ph.png" /></figure><p>First, let&#39;s log into our web server.</p><pre>$ ssh -i TutorialKeyPair.pem ec2-user@ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com</pre><pre>__|  __|_  )<br>       _|  (     /   Amazon Linux AMI<br>      ___|\___|___|</pre><pre>$</pre><p>Now you need to install <em>nfs-utils</em> to mount NFS on your server.</p><pre>$ sudo yum install -y nfs-utils</pre><p>And create a directory where web application data are stored.</p><pre>$ sudo mkdir /var/app_data</pre><p>And mount the file system using the DNS name you find in the file system detail.</p><pre>$ sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 fs-xyz.efs.us-east-1.amazonaws.com:/ /var/app_data</pre><p>Now the files you write to /var/app_data will be stored in the EFS and can be shared by any web servers that have access to the file system.</p><p>And if you&#39;d like to automatically mount the EFS when the system boots up, you may want to add one line at /etc/fstab file.</p><pre>$ vim /etc/fstab<br>#<br>LABEL=/ / ext4 defaults,noatime 1 1<br>tmpfs /dev/shm tmpfs defaults 0 0<br>devpts /dev/pts devpts gid=5,mode=620 0 0<br>sysfs /sys sysfs defaults 0 0<br>proc /proc proc defaults 0 0<br>fs-xyz.efs.us-east-1.amazonaws.com:/ /var/moodle_data nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 0 0</pre><h3>Memcached</h3><p>Now we have (almost) everything you need to get started with a simple web application. I have downloaded and installed a PHP application in this setting. However, I noticed the significant performance drop because of the usage of NFS for storage. The particular application that I used expected the storage device to be local device and create caches on the storage device. The network drive is much slower than the local device, degrade the performance of the application. One of the solutions for that was to have the application not use file storage as cache storage and use memcached for its cache storage. But first, we need to create a memcached instance to do that.</p><p>Click ElastiCache under Database section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*2xPdRSmVzA7RU9kV.png" /></figure><p>Just like we created subnet groups in MySQL database, we need to create a subnet group for ElastiCache. Click <strong>Subnet Groups</strong> from the left side navigation menu and click Create Subnet Group button. Fill in Name and Description fields and list of subnets to be added to this group. And click Create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*GBsqcAYXrXgHP1Hk.png" /></figure><p>Now click Memcached from the left side navigation menu and click <strong>Create</strong> button.</p><p>Select Memcaced radio button on Cluster engine section. Fill in the Name field. I selected smaller Node type to stay within the free tier.</p><p>Next, open the Advanced Memcahed settings section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/0*9LemwBtOB3CBPARN.png" /></figure><p>Select the Subnet group we&#39;ve just created on the Subnet group field. And click our private security group for the security group.</p><p>And click <strong>Create</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OotCmwNh3RrY_avb.png" /></figure><p>Now we have created the memcached instance. But there is one problem. We assigned our private security group to this memcahced. Our private security group does not allow memcached (port 11211). So let&#39;s allow port 11211 for our private security group.</p><p>Go to VPC&gt; Security Groups. Select Private Security Group. Open Inbound Rules tab and click Edit button. Add TCP port 11211 from the Public security group and click Save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpR0GB0Rc44bt6Fw.png" /></figure><p>Now you should have a functioning memcached and you should be able to access it from your web server.</p><p>To test the connection to the memcached, let&#39;s again login to the web server.</p><pre>$ ssh -i TutorialKeyPair.pem ec2-user@ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com</pre><pre>__|  __|_  )<br>       _|  (     /   Amazon Linux AMI<br>      ___|\___|___|</pre><pre>$</pre><p>You will need telnet to connect to memcached node and node&#39;s endpoint. In AWS console, click on the cluster name to see the list of the node. Then you will see the endpoint URL of the node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8mTYB1f_C2YGomln.png" /></figure><pre>$ sudo yum install telnet</pre><p>Let&#39;s try to connect to memcached.</p><pre>$ telnet tutorial-cache.xyz123.0001.use1.cache.amazonaws.com 11211</pre><p>Now you can run Memcahced command. Type quit to exit to the shell.</p><h4>Conclusion</h4><p>We have dealt with many concepts and services in AWS in this post. The settings we&#39;ve created in this post is far from being perfectly architected. However, I hope after this exercise, you would understand many of the concepts and practices in AWS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44ba4bbfc00d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/building-a-scalable-web-server-on-aws-44ba4bbfc00d">Building a scalable web server on AWS</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I wrote terribly slow code]]></title>
            <link>https://medium.com/sungthecoder/how-i-wrote-terribly-slow-code-468f70afae28?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/468f70afae28</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[mongoid]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Tue, 21 Mar 2017 21:19:50 GMT</pubDate>
            <atom:updated>2017-12-06T23:49:22.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGqSNWNX11o2tYced-HzeQ.jpeg" /></figure><p>It is embarrassing. But I want to write about it, so I can remember my mistake and don’t make the same error.</p><h4>Background</h4><p>I’ve been building an internal application for the laboratory for my employer. The lab receives sample materials from customers and then perform some tests on them, and send a report back to the customers. So this application tracks all the data related to the work orders, samples, and test results.</p><p>In fact, the lab has a system that’s been running more than 15 years. But it was written on ancient technology, and there is no resource or documentation for the tools available, which means it was not possible to update or upgrade the system.</p><p>So we decided to create a new system from scratch. After a long implementation phase, now I am working on migrating data from old system to the newly built system.</p><h4>Data Structure</h4><p>To make my life easier, I tried to keep the data structure as similar as the old schema. Old one uses a relational database with three main tables: work orders, samples, and test results. A work order has many samples, and a sample has many test results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*eahj3YnskZmdxxEl.png" /></figure><p>The new system uses NoSQL(MongoDB), but the basic structure stayed almost the same, except the last part: test results. In the old scheme, Test Results table holds the information about the test metadata and the result data.</p><p>In some cases, a lab technician needs to perform the same test multiple times for the same sample to calculate an average, minimum or maximum value. Then it creates multiple rows with duplicated test metadata. To reduce the redundancy of the test data and to make good use of MongoDB’s embedded documents feature, I separated Test and Results and treated Results part as embedded documents within Test document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*yP_SmHzBRSxv8v-N.png" /></figure><p>And I added a legacy_id field to the each collection to make importing easier. The legacy_id holds the primary key for the legacy database tables. I didn’t want to reuse legacy primary key for the new database.</p><h4>Importing script</h4><p>The migrating database is two step process: exporting the legacy database to Excel or CSV file and importing the data into the new system.</p><p>Since I didn’t have direct access to production data, I worked with development database, which still has a large dataset. Exporting data into CSV was easy since the legacy IDE has a feature to export the database table to Excel or CSV files. There is one exported file for each table: work_orders, samples, and test_results.</p><p>Importing process will take place in the order of work_orders, samples and test_results .</p><p>The code snippet for work_order importing is as below:</p><pre>csv = open_csv_file(&#39;workorders.csv&#39;)<br>build_hash_from_each_row(csv) do |row|<br>  create_work_order(row)<br>end</pre><ol><li>Open a CSV file</li><li>Read each row and build a Hash using the first row as keys and current row as value</li><li>Create a work order object and save it.</li><li>Repeat step 2</li></ol><p>It is simple enough, and it took about 5 min for 20,000 rows of data.</p><p>Next step is importing samples. The algorithm is almost the same. The only difference is that it need to search for related work_order with sample’s foreign key.</p><pre>csv = open_csv_file(&#39;samples.csv&#39;)<br>  build_hash_from_each_row(csv) do |row|<br>  workorder = WorkOrder.find_by(legacy_id: row[:workorder_id])<br>  create_sample(workorder, row)<br>end</pre><p>Importing sample has one more step for each row: finding its parent object, work_order.</p><p>With 60,000 rows of data, it took about 30 minutes. ‘samples.csv’ contains three times more rows than ‘workorder.csv’, but it took six times longer. Maybe because it was WorkOrder.find_by() adding a few more clock cycles and increases the total importing time. I didn’t want to worry too much. This code will run only once in production and extra 15 minutes of running were not worth of hours to investigate the cause of slowness.</p><p>The real problem started on the next importing step: test_results. The algorithm for importing test results looks almost identical to sample importing script.</p><pre>csv = open_csv_file(&#39;test_results.csv&#39;)<br>build_hash_from_each_row(csv) do |row|<br>  # Look for associated sample<br>  sample = Sample.find_by(legacy_id: row[:sample_id])</pre><pre># Look for associated test type<br>  tests = sample.tests.where(legacy_test_type_id: row[:test_type_id])</pre><pre># create a test if no test with test_type exists within the sample<br>  if tests.nil?<br>    test = build_test(sample, row)<br>  else<br>    test = tests[0]<br>  end</pre><pre># Build a result record and add it to the results list<br>  test.results &lt;&lt; build_result(row)<br>  test.save<br>end</pre><p>The above code does a little more work than the sample import script. For each row of CSV file, it (1) look for associated sample, (2) find if there are test already created for the same test type. (Tests are associated not only with a sample, but also a test_type.) If the test with the same test_type already exists, then we just append the result to its results list. Otherwise, we create a test and add the result to the results list.</p><p>The data set for test_results.csv were about 400,000 rows. It is about 6.5 times larger than samples data set. Samples importing process took 30 minutes (0.5 hours). So I guestimated test_result importing would take something between five to ten hours. Again, I didn&#39;t worry too much, because this is one-time code, and I didn&#39;t want to invest my time to optimize this code to shave a couple of hours of CPU time.</p><h3>Slow as hell</h3><p>I let my laptop run this code, configured my laptop to prevent itself from sleeping, and called for the day, expecting after a good night sleep, my computer would have taken care of this long task.</p><p>But the next morning when I open the console, I was surprised to find that the process is still running. I didn&#39;t want to wait any longer without knowing what&#39;s going on, I hit Ctrl+C and added a debugging statement to the console. Every 1000 rows imported, I have it print a total number of rows imported, and the total time elapsed.</p><p>I ran the script again; now it shows the progress information about the importing process.</p><pre>1000/382513 rows! 0.26% 96sec<br>2000/382513 rows! 0.52% 193sec<br>3000/382513 rows! 0.78% 294sec</pre><p>It takes about 100 seconds for the first 1000 rows; I calculated that it would take about 40,000 seconds for 400,000 rows, which is about 11 hours. So I told myself to be patience and let it run for a while.</p><p>Eleven hours has come and gone. I looked at the console only to find this on the screen:</p><pre>...<br>163000/382513 rows! 42.61% 39890sec<br>164000/382513 rows! 42.87% 40317sec<br>165000/382513 rows! 43.14% 40740sec<br>...</pre><p>More than 11 hours has passed, but the importing is less than 50%! How? Why?</p><h3>I found the problem!</h3><p>Let&#39;s look at the progress statement closer. In the beginning, it took less than 100 seconds for every 1000 rows. But after 11 hours, it takes more than 400 seconds! It gets slower as time goes! I plotted the time progress on a spreadsheet to plot a graph. In this chart, the x-axis represents the number of rows it processed, and the y-axis represents the time elapsed. As you can see, it shows exponential time growth. I have written O(n²) algorithm!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qHqnQtD_Sb0pC_Ul.png" /></figure><p>So I took a look at the MongoDB log file</p><pre>&gt; tail /var/log/mongodb.log<br>...<br>2016-12-27T08:49:18.996-0800 I COMMAND [conn326] command isolims_development.tests command: find { find: &quot;tests&quot;, filter: { sample_id: ObjectId(&#39;585dc8384cfad172da08652c&#39;) }, sort: { test_name: 1 } } planSummary: COLLSCAN keysExamined:0 docsExamined:136836 hasSortStage:1 cursorExhausted:1 numYields:1070 nreturned:3 reslen:7482 locks:{ Global: { acquireCount: { r: 2142 } }, MMAPV1Journal: { acquireCount: { r: 1071 } }, Database: { acquireCount: { r: 1071 } }, Collection: { acquireCount: { R: 1071 } } } protocol:op_query 159ms</pre><pre>2016-12-27T08:49:19.273-0800 I COMMAND [conn326] command isolims_development.tests command: find { find: &quot;tests&quot;, filter: { sample_id: ObjectId(&#39;585dc8384cfad172da086531&#39;), test_type_id: ObjectId(&#39;57a8603c4cfad1208858e9fc&#39;), option_value: null }, sort: { test_name: 1 } } planSummary: COLLSCAN keysExamined:0 docsExamined:136836 hasSortStage:1 cursorExhausted:1 numYields:1071 nreturned:0 reslen:124 locks:{ Global: { acquireCount: { r: 2144 } }, MMAPV1Journal: { acquireCount: { r: 1072 } }, Database: { acquireCount: { r: 1072 } }, Collection: { acquireCount: { R: 1072 } } } protocol:op_query 173ms</pre><pre>2016-12-27T08:49:19.454-0800 I COMMAND [conn326] command isolims_development.tests command: find { find: &quot;tests&quot;, filter: { test_type_id: ObjectId(&#39;57a8603c4cfad1208858e9fc&#39;), sample_id: ObjectId(&#39;585dc8384cfad172da086531&#39;), option_value: null }, projection: { _id: 1 }, limit: 1 } planSummary: COLLSCAN keysExamined:0 docsExamined:136836 cursorExhausted:1 numYields:1070 nreturned:0 reslen:124 locks:{ Global: { acquireCount: { r: 2142 } }, MMAPV1Journal: { acquireCount: { r: 1071 } }, Database: { acquireCount: { r: 1071 } }, Collection: { acquireCount: { R: 1071 } } } protocol:op_query 164ms<br>...</pre><p>MongoDB log file shows every query with an actual query command and a plan summary. I examined the planSummary and found an interesting fact. The keysExamined is always zero, and docsExamined value increases by on every time the query runs.</p><p>So this piece of code was the problem!</p><pre>test_results = sample.test_results.where(legacy_test_id: row[:test_id])</pre><p>In this code, it looks like that I am searching a test result among the small collection of sample.tests. But in reality, I was scanning through the entire list of tests. So every time I create a new record, the next search query takes longer as it scans one more document. That explains the linear increment of elapsed time.</p><p>I thought I&#39;ve written a single loop that loops through rows of test results, but there was a nested loop hidden under the where() method.</p><h3>Improvement</h3><p>I need to make the search time constant. I need to be able to find the test record in constant time regardless of the total record imported. The index is here to save my day!</p><p>As a matter of fact, I assumed that the MongoID would automatically build indexes for the belong_to association. But apparently, it is my responsibility. So I added the following code to the Samples and Tests model:</p><pre>class Test<br>  ...<br>  field legacy_test_type_id, type: Integer<br>  belongs_to :sample, index: true<br>  ...</pre><pre>index({sample_id: 1, legacy_test_type_id: 1}, {unique: true})<br>end<br>and run the command to build the index.</pre><pre>rake db:mongoid:create_indexes</pre><p>I cleared tests collection and ran the importing process again. The progress log showed the linear increment of the time elapsed as the number of imported records grow. And the MongoDB log files shows that it does not scan entire documents anymore. So I relaxed and had my laptop run this code for a while. And after 6 hours of running the importing process, it completed entire rows!</p><h4>Conclusion</h4><p>I invested couple hours for investigation and fixing the cause of slowness, and saved two days of importing time! It is not I just saved CPU time. Have I ran this in the production environment, the entire lab would have to stop their work while importing process is running. That would be a lot more expensive than one developer&#39;s time. So it was worth spending the time to improve the efficiency of the code.</p><p>A couple of things I learned here is that (1)code that looks like a single loop can be O(n²) efficiency, and it gets very slow. (2) Adding an index to the belongs_to association is my responsibility in MongoId, and it could save days of process time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=468f70afae28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/how-i-wrote-terribly-slow-code-468f70afae28">How I wrote terribly slow code</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Programming in JavaScript Way (with Beer) Part 2]]></title>
            <link>https://medium.com/sungthecoder/object-oriented-programming-in-javascript-way-with-beer-part-2-37680b05362b?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/37680b05362b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Mon, 20 Feb 2017 00:01:22 GMT</pubDate>
            <atom:updated>2017-12-06T23:55:40.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kCd5rYZne5QCo62RjvEBA.jpeg" /></figure><p>In the previous post, I intentionally didn’t mention keywords like class, this, new. I wanted to demonstrate that you can write object-oriented programming without using any of these keywords. Being able to write JavaScript using these keywords doesn’t necessary mean that your code is more advanced. It only means that you know a different way of achieving the same goal: defining and creating objects.</p><p>Although it is entirely possible to write object-oriented programming without the knowledge of the keywords mentioned above, it is best to understand the alternate path for object-oriented programming in JavaScript. As a programmer, your job is not just writing codes, but reading and understanding the intention of someone else’s’ code is as important. You don’t have to use both techniques to write your code, but you will need to understand both ways because you will never know whose code you are going to maintain in the future.</p><h4>Constructor function and new keyword</h4><p>There is one more way to create an object: new operator with a constructor function. It will look like this:</p><pre>function Beer() {<br>  /* constructor function */<br>}</pre><pre>var beer = new Beer();</pre><p>The Beer is a regular function, not a class name. However, by convention, you capitalize the name of a constructor function. That is because you want to remind yourself and other programmers that the function is intended to be used with the new operator. Inside of the constructor function, you will be using a special keyword: this. The this keyword will bind to the newly created object with the new keyword. If you call the constructor function without the new operator, this keyword will have a different meaning (global object), and your code will not produce what you intended. And it can be a source of a bug that is hard to debug.</p><p>When you call a constructor function with new keyword, the following things are happening:</p><p>1. A new empty object is created<br>2. A link(__proto__ ) between the new object and constructor function&#39;s prototype object is created. (I&#39;ll talk more about prototype object later)<br>3. this keyword in constructor function is set to the newly created object<br>4. Execute the constructor function.</p><p>Here&#39;s the Beer constructor function, that does the exactly same thing as the createBeer function in the previous post.</p><pre>function Beer(style){<br>  /* Everything here is private */<br>  var quantity = 12;<br>  function talk() { ... }<br>  function peek() { ... };<br>  function drink() { ... };<br>  function topup() { ... };</pre><pre>/* Everything included in this object will be public */<br>  this.style = style;<br>  this.talk = talk;<br>  this.peek = peek;<br>  this.drink = drink;<br>  this.topup = topup;<br>}</pre><pre>beer = new Beer();</pre><p>The beer created with the constructor function will have almost* same properties like the one created with the createBeer() function.</p><p>Note that the pattern of the function is similar to functions described earlier. The only difference is how public properties are defined at the end of the function. Instead of creating and returning an object with public properties, it assigns public properties to this object.</p><p>* There is a slight difference between objects created from createBeer() function and the new operator and a constructor function. I will explain the difference in the next section.</p><p>What about millions of objects?</p><p>If your application requires a few beers, the methods explained above would work just fine. However, if you need thousands or millions beer, you would want to find a different way of creating the objects.</p><p>The reason is that instance methods, e.g., talk, peek, drink, topup would be duplicated to all the objects. If you have thousands of objects, you are going to have several thousands of copies of functions that do exactly same things. What a wasted of memories!</p><p>What if we have an object, shared by all these million beers, that performs all the work: peek, topup and drink? Its name is &#39;<strong><em>prototype</em></strong>.&#39;</p><h3>Prototype chain</h3><p>A prototype is just a plain object. Every object has a link to a prototype object. The link from an object to its prototype object is __proto__ , pronounced &quot;dunder proto.&quot;</p><p>When you try to access a property of an object, JavaScript uses prototype chain to resolve the property value. First, it searches for its own properties. And if it can&#39;t find the property name, it moves on to its prototype object&#39;s properties. And if it still can&#39;t locate the property, it moves on again to its prototype for an additional search. This search goes on until the prototype is null.</p><p>Have you wondered why you could use toString() method on any object? Indeed, you didn&#39;t define the function, but it seems that every object responds to the method. That is because it is defined in somewhere along the prototype chain.</p><h3>Default Object prototype</h3><p>It turns out that every newly created object has prototype link(__proto__ ) to Object.prototype object. Yes, it sounds confusing: Object, prototype, and object. Let&#39;s do a small experiment. Open up a browser developer&#39;s console and type this:</p><pre>&gt; beer = {};<br>&gt; beer.__proto__ === Object.prototype<br>true<br>&gt; typeof Object.prototype<br>&quot;object&quot;<br>&gt; beer.toString()<br>&quot;[object Object]&quot;<br>&gt; beer.hasOwnProperty(&#39;toString&#39;)<br>false<br>&gt; beer.__proto__.hasOwnProperty(&#39;toString&#39;)<br>true<br>&gt; beer.__proto__.hasOwnProperty(&#39;hasOwnProperty&#39;)<br>true</pre><p>This experiment tells us many things:</p><ol><li>New object beer has __proto__ link to Object.prototype</li><li>Object.prototype is an object</li><li>Object.prototype has own properties of toString() , hasOwnProperty() .</li><li>Now you can access all the methods defined in Object.prototype , i.e.: toString() , hasOwnProperty() , etc.</li></ol><h3>Manual prototype link/Deligation</h3><p>If beer.__proto__ is just an object, can we make it be a custom made object? The answer is yes, you can do it. Let&#39;s create a drink object and have beer object&#39;s __proto__ to point to the drink object.</p><pre>var drink = {<br>  quantity: 16<br>}<br>var beer = {<br>  style: &#39;Stout&#39;,<br>  __proto__: drink<br>}<br>console.log(beer.quantity); //16</pre><p>You can even share the __proto__ object with other objects.</p><pre>var juice = {<br>  style: &#39;Orange&#39;,<br>  __proto__: drink<br>}<br>console.log(juice.quantity)l; //16</pre><h3>Linking Prototype for Constructor function</h3><p>The previous example demonstrates how the __proto__ works in JavaScript. However, I do not recommend to accessing the __proto__ property directly in your production code as I shown previously. The use of __proto__ is discouraged because:</p><ol><li>The __proto__ property was not part of the official language, but for the convenience, browser vendors started implemented it.</li><li>Although it was added to officially to ES6 for backward compatibility purpose, it is deprecated.</li></ol><h3>Object.create()</h3><p>If you want to create an object with a custom prototype, you can use Object.create(proto) method. The first argument of this method is a proto object. The newly created object will have a __proto__ link to the proto object.</p><pre>var beer = Object.create(drink);<br>beer.style = &#39;Stout&#39;;</pre><pre>var juice = Object.create(drink);<br>juice.style = &#39;Orange&#39;;</pre><h3>Constructor Function</h3><p>The more common practice of setting prototype chain is by using constructor function&#39;s prototype. Every function in JavaScript has a prototype property. Try this in a console:</p><pre>&gt; myFunction = function(){}<br>&gt; myFunction.prototype<br>Object {}</pre><p>In JavaScript, a function is an object. As it is an object, it has properties. One of its properties is prototype object. When you create an object with the new keyword with a constructor function, the newly created object&#39;s __proto__ will point to the function&#39;s prototype object. Just like:</p><pre>newObject.__proto__ = ConstructorFuction.prototype;</pre><p>Now, let&#39;s take a look at the object creation process with new operator we discussed earlier.:</p><ol><li>A new object is created</li><li>A link(__proto__ ) between the new object and constructor function’s prototype object is created.</li><li>this keyword in constructor function is set to the newly created object</li><li>Execute the constructor function.</li></ol><p>When you create an object with new operator, the newly created operator will have a link to the constructor function&#39;s prototype object. I hope that step 2 make sense now. With this knowledge, let&#39;s create a beer constructor function.</p><pre>function Beer(style, quantity){<br>  /* Everything included in this object will be public */<br>  this.quantity = quantity;<br>  this.style = style;<br>}</pre><pre>Beer.prototype.talk = function talk() { ... }<br>Beer.prototype.peek = function peek() { ... };<br>Beer.prototype.drink = function drink() { ... };<br>Beer.prototype.toptup = function topup() { ... };</pre><pre>beer = new Beer();</pre><p>Now if you inspect the beer object, you would see only two properties in the object: quantity and style.</p><pre>Object.keys(beer); // [&quot;quantity&quot;, &quot;style&quot; ]</pre><p>But, you still can make calls to all the methods: talk, peek, drink, and topup , because somewhere in prototype chain defines these methods.</p><pre>Object.keys(beer.__proto__); // [&quot;talk&quot;, &quot;peek&quot;, &quot;drink&quot;, &quot;topup&quot;]</pre><p>If you are familiar with class syntax in Classical languages like C++/C#/Java, this is the closest way to define a class in JavaScript. Objects with same class share the methods, they have their own properties. So if you are to create multiple beers, you won&#39;t have to worry about the same methods copied multiple times.</p><h3>Constructor property</h3><p>In languages like C++/C#/Java, typeof operator is a handy tool to find out the type of the object. JavaScript has typeof operator, but what it does is not very useful. Type of any object is &quot;object&quot;.</p><pre>typeof beer; // &quot;object&quot;<br>typeof {}; // &quot;object&quot;<br>typeof []; // &quot;object&quot;</pre><p>In JavaScript, constructor function has reference to prototype object and the prototype object has the reference back to its constructor function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*yfRiVfEVQpx6qQy8.png" /><figcaption>Constructor Function and prototype object</figcaption></figure><p>When a new object is created, the object&#39;s __proto__ will point to its constructor function&#39;s prototype object. Since the prototype object has a reference back to its constructor function, the object can find the reference back to its constructor function.</p><pre>beer.constructor // function Beer() {...};</pre><p>Note that unlike typeof operator; constructor property does not return a string. It returns a reference to the function itself.</p><p>It is a convenient way to find the type of object. However, I would suggest not to rely on constructor property because anyone can overwrite constructor property and it can give you a wrong answer. The better way to test object&#39;s type is instanceof operator.</p><pre>beer instanceof Beer; //true</pre><h3>Inheritance</h3><p>In classical languages like C++/C#/Java, when you call a method on an object, and the object&#39;s class doesn&#39;t have the method defined, what will happen? It looks for its parent&#39;s class and its parent&#39;s parent&#39;s class until it reaches nowhere to go. Simply put, it delegates the method to its inheritance chain.</p><p>In JavaScript, methods are delegated to its prototype chain. So you can have a similar effect by chaining object&#39;s prototypes.</p><p>Here are our Drink constructor function and its methods in the prototype.</p><pre>function Drink(quantity) {<br>  this.quantity = quantity;<br>}</pre><pre>Drink.prototype.peek = function peek() { console.log(this.quantity); };<br>Drink.prototype.drink = function drink() { this.quantiy -= 1; };</pre><p>We have a Beer constructor function. And inside of the function we didn&#39;t define any methods. All the methods are defined at the Drink function&#39;s prototype object.</p><p>So an object created with new operator and Drink constructor function will have a __proto__ point to the Drink function&#39;s prototype object, which has peek and drink methods.</p><p>Now, let&#39;s create a Beer constructor function and have its prototype object link to Drink&#39;s prototype object.</p><pre>function Beer(quantity, style) {<br> // Calling parent&#39;s constructor<br> Drink.call(this, quantity);<br> this.style = style;<br>}</pre><pre>// Replace Beer&#39;s prototype with Drink&#39;s prototype.<br>// Create an empty object with its prototype link to Dirnk&#39;s prototype.<br>Beer.prototype = Object.create(Drink.prototype);<br>// The newly created prototype object&#39;s constructor is Drink. We want it to be Beer. <br>Beer.prototype.constructor = Beer;</pre><pre>// Beer specific methods.<br>Beer.prototype.checkId = function checkId(id){ ... };<br><br>Let&#39;s create a beer and see what&#39;s inside!</pre><pre>var beer = new Beer(12, &quot;Larger&quot;);<br>Object.keys(beer);<br>[&quot;quantity&quot;, &quot;style&quot;]</pre><pre>Object.keys(beer.__proto__);<br>[&quot;constructor&quot;, &quot;checkId&quot;]</pre><pre>Object.keys(beer.__proto__.__proto__);<br>[&quot;peek&quot;, &quot;drink&quot;]<br></pre><p>Now you can find all the methods through prototype chain: a beer object contains quantity and style properties. Its prototype has the beer specific methods and beer&#39;s prototype&#39;s prototype includes methods of its parent, Drink.</p><p>There are a couple of things that I would consider the drawback of using constructor function:</p><p>The first is that its syntax is inside out. Unlike other classical languages where every method and property are nicely contained within a single curly bracket, constructor function and all other methods are separated into different functions. It is something I found hard to get used to.</p><p>Another drawback is that it become very hard to have a private method or property. You still can define a private property within constructor function just like we did with the factory function: defining a simple local variable within a function. However, the instance methods will not have access to the variable, since the functions are defined outside of constructor function because JavaScript&#39;s variables are function scoped.</p><p>If you really need private property, all the methods that need access to the private variables must be defined inside of constructor function. Here&#39;s an example.</p><pre>function SomethingToHide() {<br>  // Private Parts<br>  var hidden;</pre><pre>// Public Parts<br>  this.publicVar = null;<br>  this.accessHidden = function accessHidden(){<br>    // do something with hidden<br>  };<br>}</pre><p>SomethingToHide.prototype.publicMethid = function (){};<br><br>Now the code becomes much harder to read and maintain. Some functions are inside; some are outside. You will have to decide which one should be in or out.</p><h3>Class in JavaScript</h3><p>To solve one of the drawbacks in the previous section, the newer version of JavaScript, ES6 introduced class keyword. But there is a reason that I didn&#39;t mention class keyword until the last moment. That&#39;s because it is not a new feature of the language. It is merely syntactic sugar for constructor function. So it is important to understand what is happening behind the scene and I wanted to make sure to cover that.</p><p>With new syntax, creating class becomes much easier.</p><pre>class Beer {<br>  constructor(quantity, style) {<br>    this.quantity = quantity;<br>    this.style = style;<br>  }<br>  talk() { ... }<br>  peek() { ... }<br>}</pre><pre>var beer = new Beer(12, &quot;IPA&quot;);<br>Writing inheritance is also much easier.</pre><pre>class Beer extends Drink {<br>  constructor(quantity, stype) {<br>    super(quantity);<br>    this.style = style;<br>  }<br>  // beer methods...<br>}</pre><p>If you want to use class keyword today, you may want to use transpiler (source code to source code compiler) like Babel to translate your code into constructor function and prototypes. At the moment, not all the browser support class keyword.</p><h3>Conclusion</h3><p>We have covered a lot about Object Oriente programming in JavaScript. We have learned how to create literal objects, how to build an object with createFunction, Object.create() method and constructor function. We also learned about JavaScript object&#39;s prototype chain. And we have learned the new JavaScript&#39;s syntax to create objects: class.</p><p>So what is the best way to create objects in JavaScript? The answer is: it depends. If you just need a simple collection of data, I would use the literal objects. If you need not only collection of data but methods against the data, I will go with the class keyword (and transpiler). And if the security is the concern and you must hide the internals of the object, createFunction would be my choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37680b05362b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/object-oriented-programming-in-javascript-way-with-beer-part-2-37680b05362b">Object Oriented Programming in JavaScript Way (with Beer) Part 2</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Programming in JavaScript Way (with Beer)]]></title>
            <link>https://medium.com/sungthecoder/object-oriented-programming-in-javascript-way-with-beer-70517106c42e?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/70517106c42e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Mon, 06 Feb 2017 00:01:01 GMT</pubDate>
            <atom:updated>2017-12-06T23:05:32.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-V64I8HpaO5OnFdscAbsA.jpeg" /></figure><p>If you have experience with Object Oriented Programming (OOP) with Java or C++, and you’d like to learn JavaScript, then you may find its object construction confusing. When it comes to OOP, JavaScript takes slightly different approach. One major feature is its lack of class.</p><h3>There is no class!</h3><p>When you create an object in Java, you would need a class first:</p><pre>public class Beer {<br>  Beer(String style){<br>    /* Constructor */<br>  }<br>  String style; /* Instance Variable */<br>  void makesHappy(Person drinker) {<br>    /* Instance Method */<br>  }<br>}</pre><p>Once you have a class, you can create an object.</p><pre>Beer myBeer = new Beer();</pre><p>In JavaScript, it is much simpler. You skip the creating class. Just create an object.</p><pre>var beer = {};</pre><p>That’s it. Now you know how to create an object in JavaScript. Wait, how about attributes and methods? That’s easy:</p><pre>var beer = {<br>  style: &quot;IPA&quot;,<br>  makesHappy: function(drinker){ }<br>};</pre><p>JavaScript object is nothing but key, value pair. In other languages, it is called hash map, dictionary or associative array. The type of the value can be any primitive values (number, string or boolean), object (another key, value pairs), array or function. For keys, there is only one type: string.</p><p>Although you can use any string for object key, it is a good idea to conform to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables">JavaScript identifier rule</a>. One benefit of submitting to identifier rule is that you can use dot(.) notation to access the instance variable or methods. If you have to use a non-conforming key, you still can access the value using square brackets notations:</p><pre>beer.origin = &quot;German&quot;;<br>beer[&quot;origin&quot;] = &quot;German&quot;;</pre><pre>beer[&quot;alcohole-content&quot;] = &quot;5%&quot;;<br>beer.alcohole-content = &quot;5%&quot;; //Error!</pre><h3>Blueprint</h3><p>The Nice thing about the class definition is that the class serves as the blueprint of objects. It has all the definitions of objects to be created. If you need only one object of the same type for your application, creating a class or blueprint for the object may be overwork. So creating an object literal as describe above makes perfect sense. However, if you are expecting to build multiple objects with a similar signature, you may want to use a function that creates and returns objects.</p><pre>function createBeer(style){<br>  return {<br>    style: style,<br>    makeHappy: function(drinker){ },<br>    talk: function() {<br>      console.log(&quot;Hello, I am &quot; + this.style);<br>    }<br>  };<br>}</pre><p>With this function, you can create objects with the same property signature.</p><pre>var myBeer = createBeer(&quot;IPA&quot;);<br>var yourBeer = createBeer(&quot;Stout&quot;);</pre><pre>myBeer.talk();<br>// Hello, I am IPA<br>yourBeer.talk();<br>// Hello, I am Stout</pre><h3>Encapsulation: Revealing module pattern</h3><p>In JavaScript object, everything is public. If you want to define private variable or methods, you can prefix underscore(&#39;_&#39;) in the key. However, these underscore prefixed variables are still public and can be accessed by anyone.</p><p>If you&#39;d like some real privacy, you can use the same create method as shown above. But define the private members outside the returning object. Let&#39;s say that our beer has a private variable, quantity , and it can be accessed only by instance methods: peek, drink and topup. Here&#39;s how it looks:</p><pre>function createBeer(style){<br>  var quantity = 12;</pre><pre>return {<br>    style: style,<br>    talk: function() {<br>      console.log(&quot;Hello, I am &quot; + style);<br>    },<br>    peek: function() { return quantity; },<br>    drink: function() { quantity -= 1; },<br>    topup: function() { quantity = 12; }<br>  };<br>}</pre><p>Note that the variable, quantity, is defined outside of the returning object. And the functions in the returning objects: peek, drink and topup, refer to the variable, quantity. Since the variable, quantity, is not part of the object, it is not possible to access the variable directly. However since the methods, peek(), drink() and topup(), are defined inside of the beerFactory function, they have access to any variable inside the beerFactory function.</p><p>And make sure not to add this keyword before the variable, quantity. That is because the variable quantity is a local variable within the createBeer function, not part of the object.</p><pre>var myBeer = beerFactory(&quot;IPA&quot;);<br>myBeer.quantity<br>// undefined<br>myBeer.peek()<br>// 12<br>myBeer.drink();<br>myBeer.peek();<br>// 11<br>myBeer.topup();<br>myBeer.peek();<br>// 12</pre><p>If you don&#39;t remember anything I&#39;ve just said, try to remember ONE thing: All the variables and functions defined in the create<em>Object</em> function are private until you include them inside the returned object.</p><h3>Make it more readable</h3><p>If you have long method body within the returning object, the code may become hard to read and maintain. Here&#39;s the way to make it a little bit cleaner:</p><pre>function beerFactory(style){<br>  /* Everything here is private */<br>  var quantity = 12;<br>  function talk() { ... }<br>  function peek() { ... };<br>  function drink() { ... };<br>  function topup() { ... };</pre><pre>/* Everything included in this object will be public */<br>  return {<br>    style: style,<br>    talk: talk,<br>    drink: drink,<br>    topup: topup<br>  };<br>}</pre><p>If you are writing in ES6, you can make the return statement shorter by writing:</p><pre>return { style, talk, drink, topup };</pre><p>In ES6, if you create an object with the list of variable names, it will assume that the key is the name of the variable.</p><h3>Inheritance</h3><p>One important feature of object-oriented programming is inheritance. Inheritance allows us to have access to the methods or instance variables from the parent class. In another word, the object will have not just properties of its own but also someone else&#39;s properties.</p><p>One of the ways to achieve this effect is by merging two objects.</p><pre>drink = {<br>  quantity: 12<br>}</pre><pre>beer = {<br>  alcoholContent: 0.05<br>}</pre><pre>myBeer = Object.assign({}, drink, beer);<br>// { quantity: 12, alcoholContent: 0.05 }</pre><p>Now myBeer has properties of both drink and beer.</p><h3>Composition, mixin</h3><p>Here is a bad news. There is no inheritance in JavaScript. But before you dismiss JavaScript due to the lack of inheritance, think again: why do we need inheritance? If we need one object share properties of other objects, is there any other way to achieve this goal?<br>The answer is yes; we can use a mixin. Merging two or more objects in object creation function just like we saw in the previous section.</p><p>Let&#39;s create an object creation function for Drink. And let our beer objects share properties of drink objects.</p><pre>function createDrink(size) {<br>  function peek() { ... };<br>  function drink() { ... };<br>  function topup() { ... };</pre><pre>return {<br>    peek: peek,<br>    drink: drink,<br>    topup: topup<br>  };<br>}</pre><p>CreateDrink function creates a drink object with methods related to any beverages: peek, drink, topup.</p><p>Since we want the beer object to share the properties of a drink object, we create a drink object inside of createBeer.</p><pre>function createBeer(size, alcohol) {<br>  var drink = createDrink(size);<br>  function checkId() { ... }</pre><pre>return Object.assign(drink, {<br>    talk: talk<br>  });<br>}</pre><p>In beerFactory, four things are happening in the two highlighted lines.<br>1. It creates a drink object by calling createDrink.<br>2. It creates a beer object.<br>3. Merge drink object and beer object<br>4. Return the merged object.</p><p>Now the beer object is effectively inherited from drink object.</p><p>But isn&#39;t my object too flexible?</p><p>Now you have a function that creates objects in an expected format with private members and shares some properties from parent objects. That covers almost all aspect of object creation in object oriented programming. However, you may feel something is not right. You can create objects, but these objects are simply key value pairs. Anybody can add or remove properties to the objects. In a large application, this can be a very difficult to manage. This problem can be solved with one method: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">Object.freez()</a>.</p><p>Right before you return the object, you can freeze the object. So the object cannot be altered after its creation. Here&#39;s the final form of the function.</p><pre>function createChild(spec){<br>  /* inheritance */<br>  var parent = createParent(spec);</pre><pre>/* private members */<br>  var privateVal;<br>  function privateMethod() {...}<br>  function publicMethod() {..}</pre><pre>/* creating an frozen object with public members */<br>  return Object.freeze(Object.assign(parent, {<br>    publicMethod: publicMethod,<br>    ...<br>  });<br>}</pre><p>Now the created object is frozen, the user of the object cannot add or remove properties from the object. But they still can call methods, access the values in the object just like a normal object.</p><h3>Conclusion</h3><p>That&#39;s it! This is all you need to know about object-oriented programming in JavaScript. You may ask where is the new keyword? How about &#39;this&#39; keyword? In JavaScript, these two keywords have slightly different meaning from the ones in classical Object Oriented languages like Java or C++. So you may feel like home if you see these syntaxes, but they can be a trap (a potential source of bug that is hard to catch) if you start using it without fully understand them. So it is important to understand JavaScript way of creating objects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70517106c42e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/object-oriented-programming-in-javascript-way-with-beer-70517106c42e">Object Oriented Programming in JavaScript Way (with Beer)</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to have Angular2 and Rails coexist peacefully on your laptop and servers]]></title>
            <link>https://medium.com/sungthecoder/how-to-have-angular2-and-rails-coexist-peacefully-on-your-laptop-and-servers-2f3ab380af62?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f3ab380af62</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Tue, 24 Jan 2017 03:48:55 GMT</pubDate>
            <atom:updated>2017-12-06T23:33:06.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mv4GO_6l7gK-USUHZoRYiA.jpeg" /></figure><p>Most of the front-end tutorials assume that your JS application runs on a separate server to the backend application and the front-end code has different codebase. It makes sense when you have independent teams to develop the front-end and the backend. But if you work in a small team of full stack developers, having separate codebase becomes an overhead.</p><p>One option of integrating the Angular app with Rails would be putting all javascript code within Rails directory structure, i.e., ‘app/assets/javascript.’</p><p>However, this option only makes sense when you have a little JavaScript code, and you want Rails asset pipeline to concatenate all your javascript codes. So most of the case, this would not be the solution because:</p><ol><li>TypeScript is the language choice of Anguar2. And Rails’ asset pipeline does not know how to handle typescript. You don’t have to write an Angular2 app in TypeScript, but you don’t want to give up the option just because the environment you chose.</li><li>And the Angualar2 app may want to be treated as the first class app. Angular2 app will play vital importance in your whole application. Placing that critical code somewhere deep inside the closet, ‘app/assets/javascript/ng2-app/…’ doesn’t seem to be very nice.</li></ol><p>In this article, I would like to show how to configure Rails and Angular2, so that Rails app and the Angular2 app can coexist within one repository.</p><p>Followings are the result I would like to achieve at the end of this article:</p><ul><li>Your Angular2 app’s source code lives in an independent directory structure, e.g. ‘RAILS_ROOT/ng2-app’</li><li>Your Angular2 Service can use relative path for API calls because they will live on the same server. No need for CORS configuration.</li><li>During development, you can use rails development server and angular development server. Rails server provides all the API calls, and Angular2 server helps you with the Angular2 app.</li><li>At deployment time, asset precompile will include your Angular 2 bundles so that Rails controller can serve the Angular2 app.</li></ul><h3>1. Create a Rails app.</h3><p>The first thing you would need is a working Rails app. If you already have an existing rails app, that’s great. But if you’d like to start from scratch, here’s how we start.</p><p>Let’s create a Rails app and call it ‘rails_ng2.’</p><pre>$ rails new rails_ng2<br>$ cd rails_ng2</pre><p>And let’s add a resource and call it ‘<strong>widget</strong>.’ The widget has three properties: name, description, and price.</p><pre>$ rails g scaffold Widget name description price:float</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*niGrC8iB5_AbnRju.png" /></figure><p>Let’s migrate the database.</p><pre>$ rake db:migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r98eN5l0jPT0VHKJ.png" /></figure><p>Run the rails development server</p><pre>$ rails s</pre><p>Then you already have a working Rails app! Point your browser to <a href="http://localhost:3000/widgets;">http://localhost:3000/widgets;</a> then you should be able to view and create some widgets.</p><p>[caption id=”attachment_104&quot; align=”aligncenter” width=”804&quot;]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*DCy8DS0XJIDDBNTs.png" /></figure><p>widgets page[/caption]</p><h3>2. Add API endpoint</h3><p>Now it’s time to build API endpoints for these widgets you’ve just created. It seems to be redundant to write another controller for the same behavior, but they serve two different audiences(human vs. machine) and purposes(rendering HTML and providing data). So it is always a good idea to create a separate endpoint for APIs.</p><p>With Rails, it is always easy to create another controller:</p><pre>$ rails g controller api/widgets</pre><p>And edit widgets controller file.</p><pre>class Api::WidgetsController &lt; ApplicationController<br>  before_action :set_widget, only: [:show, :update, :destroy]<br>  respond_to :json</pre><pre>def index<br>    @widgets = Widget.all<br>    render json: @widgets<br>  end</pre><pre>def show<br>    render json: @widget<br>  end</pre><pre>def create<br>    @widget = Widget.new(widget_params)<br>    if @widget.save<br>      render json: @widget<br>    else<br>      render json: @widget.errors, status: :unprocessable_entity<br>    end<br>  end</pre><pre>def update<br>    if @widget.update(widget_params)<br>      render json: @widget<br>    else<br>      render json: @widget.errors, status: :unprocessable_entity<br>    end<br>  end</pre><pre>def destroy<br>    @widget.destroy<br>    head :no_content<br>  end</pre><pre>private<br>  # Use callbacks to share common setup or constraints between actions.<br>  def set_widget<br>    @widget = Widget.find(params[:id])<br>  end</pre><pre># Never trust parameters from the scary internet, only allow the white list through.<br>  def widget_params<br>    params.require(:widget).permit(:name, :description, :price)<br>  end<br>end<br></pre><p>Add the controller to the route configuration.</p><pre>namespace :api do<br>  resources :widgets<br>end</pre><p>You can point your browser to <a href="http://localhost:3000/api/widgets"><strong>http://localhost:3000/api/widgets</strong></a> and see JSON representation for your widget resources.</p><h3>3. Add Angular2 App</h3><p>Now you have a working Rails app and API endpoint; it&#39;s time to build an Angular2 app to consume the API.</p><p>With Angular CLI, it becomes easy to create an angular2 app. If you don&#39;t have Angular CLI, install it with npm.</p><pre>$ npm install -g angular-cli</pre><p>And create an Angular2 app:</p><pre>$ ng new ng2-app</pre><p>This command will create an Angular2 app under &#39;ng-app&#39; directory.</p><pre>$ cd ng2-app<br>ng2-app$ npm start</pre><p>Point your browser to <a href="http://localhost:4200/"><strong>http://localhost:4200</strong></a> and you will see this.</p><figure><img alt="App works!" src="https://cdn-images-1.medium.com/max/970/0*3vnAsphv4ruFp-7c.png" /><figcaption>app works!</figcaption></figure><h3>4. Add components and routing to the Angular2 app</h3><p>Let&#39;s create two components; home and widgets. With Angular CLI, it is one line task:</p><pre>ng2-app$ ng g component widgets<br> create src/app/widgets/widgets.component.css<br> create src/app/widgets/widgets.component.html<br> create src/app/widgets/widgets.component.spec.ts<br> create src/app/widgets/widgets.component.ts<br>ng2-app$ ng g component home<br> create src/app/home/home.component.css<br> create src/app/home/home.component.html<br> create src/app/home/home.component.spec.ts<br> create src/app/home/home.component.ts</pre><p>Let&#39;s add a router to load one of these components based on your URL.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { Routes, RouterModule } from &#39;@angular/router&#39;;<br>import { WidgetsComponent } from &#39;./widgets/widgets.component&#39;;<br>import { HomeComponent } from &#39;./home/home.component&#39;;</pre><pre>const routes: Routes = [<br>  {path: &#39;&#39;, component: HomeComponent},<br>  {path: &#39;widgets&#39;, component: WidgetsComponent },<br>  {path: &#39;*&#39;, redirectTo: &#39;&#39;}<br>];</pre><pre>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule],<br>  providers: []<br>})<br>export class Ng2RestAppRoutingModule { }</pre><p>This routing configuration will have our app to load Widgets Component when we point the browser URL to &#39;/widgets&#39; or Home Component otherwise.</p><p>And we will have to tell where to load these components. Add &lt;router-outlet&gt;&lt;/router-outlet&gt; at the end of &#39;<strong>ng-app/src/app/app.component.html</strong>&#39;</p><p>And for our convenience, let&#39;s add a navigation menu to app component template.</p><pre>&lt;h1&gt; {{title}} &lt;/h1&gt;</pre><pre>&lt;nav class=&quot;mdl-navigation&quot;&gt;<br>  &lt;a [routerLink]=&quot;links.home&quot;&gt;Home&lt;/a&gt;<br>  &lt;a [routerLink]=&quot;links.widgets&gt;Widgets&lt;/a&gt;<br>&lt;/nav&gt;</pre><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>And let&#39;s add it to the component class.</p><pre>import { Component } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent {<br>  title = &#39;app works!&#39;;<br>  links = {<br>    home: [&#39;/&#39;],<br>    widgets: [&#39;/widgets&#39;]<br>  };<br>}</pre><p>Now we will have to wire all these modules in app.module.ts</p><pre>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { HttpModule } from &#39;@angular/http&#39;;<br>import { Ng2RestAppRoutingModule } from &#39;./app-routing.module&#39;;</pre><pre>import { AppComponent } from &#39;./app.component&#39;;<br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { WidgetsComponent } from &#39;./widgets/widgets.component&#39;;</pre><pre>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    HomeComponent,<br>    WidgetsComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    FormsModule,<br>    HttpModule,<br>    Ng2RestAppRoutingModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>At this point, you should be able to run the Angular2 app on the separate development server, i.e., ng serve. You can click the navigation button and see it loads home and widgets components.</p><h3>5. Add a Service</h3><p>Now we have built two separate apps: Rails app and Angular2 app, but they are not connected anyhow. In this step, we will create a service that can consume API that we&#39;ve just set up on Rails app.</p><p>Angular CLI have service generator, but unlike the component generator, it creates files in the current directory. So we will have to create a directory and cd into the directory where we want the service modules to reside.</p><pre>ng2-app/src/app$ mkdir shared<br>ng2-app/src/app$ cd shared<br>ng2-app/src/app/shared$ ng g service widgets<br> create src/app/shared/widgets.service.spec.ts<br> create src/app/shared/widgets.service.ts</pre><p>Let&#39;s edit widgets service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Http, Response } from &#39;@angular/http&#39;;<br>import { Observable } from &#39;rxjs/Observable&#39;;<br>import &#39;rxjs/add/operator/map&#39;;</pre><pre>@Injectable()<br>  export class WidgetsService {<br>  private url = &#39;api/widgets&#39;;</pre><pre>constructor (private http: Http) {}</pre><pre>getWidgets() {<br>    return this.http.get(this.url)<br>      .map(res=&gt; res.json())<br>  }<br>}</pre><p>Note that we didn&#39;t add &#39;http://localhost:3000&#39; suffix to the URL. We treat the API URL as if they are from the same origin.</p><p>Let&#39;s use this service on our widgets component:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { WidgetsService } from &#39;../shared/widgets.service&#39;</pre><pre>@Component({<br>  selector: &#39;app-widgets&#39;,<br>  templateUrl: &#39;./widgets.component.html&#39;,<br>  styleUrls: [&#39;./widgets.component.css&#39;]<br>})<br>export class WidgetsComponent implements OnInit {<br>  constructor (private widgetsService: WidgetsService) {}<br>  widgets = []</pre><pre>ngOnInit() {<br>    this.widgetsService.getWidgets().<br>    subscribe(widgets =&gt; this.widgets = widgets)<br>  }<br>}</pre><p>And update the template to display widgets object:</p><pre>&lt;p&gt;<br>  widgets works!<br>&lt;/p&gt;</pre><pre>&lt;pre&gt;<br>  {{ widgets | json }}<br>&lt;/pre&gt;</pre><p>And add the service module to the app modules.</p><pre>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { HttpModule } from &#39;@angular/http&#39;;<br>import { Ng2RestAppRoutingModule } from &#39;./app-routing.module&#39;;</pre><pre>import { AppComponent } from &#39;./app.component&#39;;<br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { WidgetsComponent } from &#39;./widgets/widgets.component&#39;;</pre><pre>import { WidgetsService } from &#39;./shared/widgets.service&#39;;</pre><pre>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    HomeComponent,<br>    WidgetsComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    FormsModule,<br>    HttpModule,<br>    Ng2RestAppRoutingModule<br>  ],<br>  providers: [<br>    WidgetsService<br>  ],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>If you run your Angular2 app and load Widgets Component, you will see 404 error on the developer console. That is because we do not have anything on <a href="http://localhost:4200/api/widgets.">http://localhost:4200/api/widgets.</a> Our backend server is running on <a href="http://localhost:3000/api/widgets.">http://localhost:3000/api/widgets.</a> So we have to tell our Angular server to look at <a href="http://localhost:3000/">http://localhost:3000</a> when we make an API call.</p><h3>6. Add dev server API proxy</h3><p>In this step, we will tell Angular development server to look for <strong>localhost:3000</strong> when we ask for something from <strong>/</strong>api<strong>/*</strong>.</p><p>First, you will have to create a proxy configuration file.</p><pre>{<br>  &quot;/api&quot;: {<br>    &quot;target&quot;: &quot;http://localhost:3000&quot;,<br>    &quot;secure&quot;: false<br>  }<br>}</pre><p>This configuration tells that when you see &#39;/api&#39; prefix in your URL, forward the message to &#39;http://localhost:3000&#39;.</p><p>And let&#39;s have our development server to use this proxy configuration. Open &quot;package.json&quot; file and replace start script with following:</p><p>&quot;start&quot;: &quot;ng serve --proxy-config proxy.config.json&quot;</p><p>Now, restart your Angular2 development server, you should see Widgets Component load all the widgets in JSON format!</p><p>Congratulations! You successfully wired Rails app and Angular2 app. You can do both frontend and backend development in one directory structure. Add more API endpoints; then you should be able to use them right away from your Angular2 app.</p><h3>7. Add controller to serve the Angular2 app</h3><p>We&#39;ve made a big progress, but we didn&#39;t finish yet. Our ultimate goal is to have the Angular2 app available under our Rails app, not two separate servers: rails server running on port 3000, Angular server running on port 4200. Then we need to create a controller for our Angular2 app and router to call the controller.</p><pre>$ rails g controller ng2_app</pre><p>Let&#39;s add the route to the configuration.</p><pre>get &quot;ng2-app&quot;,       controller: &quot;ng2_app&quot;, action: &quot;index&quot;<br>get &quot;ng2-app/*path&quot;, controller: &quot;ng2_app&quot;, action: &quot;index&quot;</pre><p>These two lines will let Rails to call index method on the Ng2AppController we&#39;ve just created. We need to have these two lines so that Rails can ignore additional paths after &#39;localhost:3000/ng2-app/, but Angular2 app will read path and decide its actions.</p><p>For example, if we enter &#39;http://domain-name.com/ng2-app&#39;, Rails will call index method of Ng2AppController. And then our Angular2 app&#39;s routing system will decide to load Home Component.<br>But if we enter &#39;http://domain-name.com/ng2-app/widgets&#39;, Rails will ignore the last part: &#39;widgets&#39; and still call index method of Ng2AppController. And the Anguar2 app&#39;s routing will read the last part of the URL and load Widgets Component.</p><p>Since we don&#39;t have any method defined in NgAppController, let&#39;s add the method.</p><pre>class Ng2AppController &lt; ApplicationController<br>  def index<br>  end<br>end</pre><p>And we need the view for this action.</p><pre>&lt;% content_for :head do %&gt;<br>&lt;base href=&quot;/ng2-app&quot;&gt;<br>&lt;% end %&gt;</pre><pre>&lt;app-root&gt;Loading...&lt;/app-root&gt;</pre><pre>&lt;%= javascript_include_tag &quot;ng2-app/inline&quot; %&gt;<br>&lt;%= javascript_include_tag &quot;ng2-app/styles.bundle&quot; %&gt;<br>&lt;%= javascript_include_tag &quot;ng2-app/main.bundle&quot; %&gt;</pre><p>A few things are going on in this file:</p><ul><li>&lt;base href=”/ng2-app”&gt; tells the Angular2 app to ignore first ‘/ng2-app’ from the path. For example, if the URL of the browser is pointing to ‘http://domain-name.com/ng2-app<strong>/</strong>&#39;, Anguar2 will only look at ‘<strong>/</strong>’ and load Home Component. And if it sees ‘http://domain-nam.com/ng2-app<strong>/widgets</strong>&#39;, it will recognize ‘<strong>/widgets</strong>’ and serve Widgets Component.</li><li>We must put this &lt;base&gt; tag within &lt;head&gt; tag, so we are wrapping &lt;base&gt; tag between &lt;coneten_for :head&gt;. We are going to add another yield statement in the layout file later.</li><li>&lt;app-root&gt;Loading…&lt;/app-root&gt; is where the Angular2 app will live.</li><li>When you build the Angular2 app with ‘ng build,’ it will generate three files: ‘inline.js’, ‘styles.bundle.js’ and ‘main.bundle.js’ into ‘ng2-app/dist/’ directory. So we are loading these three files into our view template. Note that ‘ng2-app/’ prefix of the javascript filenames are not necessary. However, if you are planning to add more than one Anguar2 app under the same project, it is better to add the subdirectory.</li></ul><p>Let&#39;s open the application.html.erb and add one more line right before the closing tag of &lt;/head&gt;</p><pre>&lt;%= yield :head %&gt;</pre><p>Now you open up the browser, and load &#39;http://localhost:3000/ng2-app&#39; then you will see &#39;Loading...&#39; but nothing happens. And the browser console will spit out 404 error for all the javascript files we try to load. That&#39;s because Rails cannot find the javascript files we included in &lt;%= javascript_include_tag %&gt; .</p><h3>8. Let Rails know where to find Anuglar2 app</h3><p>By default, Rails look for &#39;app/assets/javascript&#39; and &#39;lib/assets/javascript&#39;, &#39;vendor/assets/javascript&#39; directory to find the files we stated in &lt;%= javascript_include_tag %&gt; . But our Angular2 app does not reside on any of those directories. One solution would be copying Angular2 app files to one of standard search directories, but then we will have to copy files every time we build the Angular2 app and it&#39;s too much work (I&#39;m lazy). Instead, let&#39;s teach Rails where to search.</p><p>Open &#39;config/application.rb&#39; and add the following line between the &#39;class Application &lt; Rails::Application&#39; and &#39;end&#39;:</p><p>config.assets.paths &lt;&lt; Rails.root.join(&quot;ng2-app&quot;, &quot;dist&quot;)</p><p>This one line will tell Rails to look &#39;RAILS_ROOT/ng2-app/dist/&#39; directory in addition to the Rails default asset paths for JavaScript files. So Rails will turn &lt;%= javascript_include_tag &quot;ng2-app/inline&quot; %&gt; into &lt;script src=&#39;ng2-app/dist/ng2-app/inline.js&#39;&gt; for development environment.</p><p>But in the production environment, Rails will look for &#39;/public/assets/ng-app/inline.[MD5-hash].js&#39;. You will also have to tell Rails to include these file for precompilation. In order for that add the following line in &quot;config/initializers/assets.rb&quot;</p><p>Rails.application.config.assets.precompile +=<br> %w( ng2-app/inline.js ng2-app/styles.bundle.js ng2-app/main.bundle.js)</p><p>The last step is to tell Angular2 to place bundle files into &#39;dist/ng2-app/&#39; instead of &#39;dist/.&#39; Open &#39;ng2-app/angular-cli.json&#39;. And change apps[&quot;outDir&quot;] value to dist/ng2-app.</p><pre>{<br>  ...<br>  &quot;apps&quot;: {<br>    ...<br>    &quot;outDir&quot;: &#39;dist/ng2-app&#39;<br>    ...<br>  }<br>}</pre><p>Rebuild your Angular2 app with ng build and restart Rails server with rails s ; then you should be able to see your Angular2 app working on &#39;http://localhost:3000/ng2-app&#39;.</p><p>You may wonder why we bother to place our Angular2 app bundle files on &#39;dist/ng2-app&#39; instead of the default &#39;dist/&#39; directory. There are two reasons for that: self-documentation and future-proof.<br>Have left all the bundle files under &#39;dist/&#39; directory, we could include the javascript files in our Rails view file like this: &lt;%= javascript_include_tag &#39;main.bundle&#39; %&gt; or &lt;%= javascript_include_tag &#39;inline&#39; %&gt; . But then, two months later, you come back to this code and might have forgotten what the &#39;min.bundle&#39; or &#39;inline&#39; are. It would be easier to remember to if you write &#39;ng2-app/main.bundle&#39; or &#39;ng2-app/inline&#39;.</p><p>Imagine six months later; your client wants to add another Single Page App under the same Rails app. That&#39;s easy. You create &#39;another-app&#39; directory on the RAILS_ROOT directory for another Angular2 app. And add config.assets.paths &lt;&lt; Rails.root.join(&quot;another-app&quot;, &quot;dist&quot;) to your application.rb file. And your view file, you include the javascript bundles: &lt;%= javascript_include_tag &#39;main.bundle&#39; %&gt; . Now you see the problem? Rails will include the JavaScript files from &#39;ng-app/dist/&#39; directory, not from &#39;another-app/dist/&#39; directory, because it will find main.bundle.js file from &#39;ng-app/dist&#39; directory first.</p><p>Instead of a directory location, we could have changed bundled file name with a suffix, e.g., ng2-app.main.bundle.js, ng2-app.inline.js, etc. But at the moment, there is no option to change bundled file name in Angular CLI configuration, so I decided to change its build target directory: &#39;ng2-app/main.bundle.js&#39; instead of &#39;ng2-app.main.bundle.js&#39;.</p><h3>9. Deploying to Heroku</h3><p>This section is optional if you&#39;d like to deploy your app to Heroku.</p><p>The small disadvantage of this approach is that you can&#39;t have Heroku handle its asset precompilation process. Before precompilation assets, you will have to run ng build on your Angular2 app. That means you will have to push precompiled assets to Heroku.</p><p>At a minimum, you will need pg and rails_12factor gem for Heroku deployment. Add these two gems in your Gemfile.</p><pre>group :production do<br>  # Heroku recommended gem<br>  gem &#39;pg&#39;<br>  gem &#39;rails_12factor&#39;<br>end</pre><p>And install gems: bundle install</p><p>Initialize your GIT repository. And commit the files.</p><pre>$ git init<br>$ git add .<br>$ git commit -m &quot;initial commit&quot;</pre><p>Now, create a Heroku server to deploy your app: heroku create</p><p>I don&#39;t like to litter my master branch with precompiled assets in public directory. So I prefer to create a dist branch for deployment.</p><pre>$ git co -b dist # create and switch to the dist branch<br>(dist)$ rake assets:clobber # remove old assets<br>(dist)$ (cd ng2-app; ng build) # build Angular2 app<br>(dist)$ RAILS_ENV=production rake assets:precompile # precompile assets<br>(dist)$ git add --all<br>(dist)$ git commit -m &quot;initial deployment&quot; # commit the change<br>(dist)$ git push heroku dist:master # push dist branch to heroku&#39;s master</pre><p>These are a lot of steps to remember. You will have to:</p><ol><li>create and switch to a dist branch</li><li>remove all old assets</li><li>build the Anuglar2 app</li><li>precompile assets</li><li>commit the changes</li><li>and push the changes to Heroku.</li></ol><p>I usually let CI server handle all these steps, so once I set this process up, I do not have to remember.</p><p>Now your Rails+Angular2 app is in the world of the internet! If you see 404 error on the home page in this particular example, don&#39;t panic. That&#39;s because we didn&#39;t create a home page; we didn&#39;t create a controller nor routing for &#39;/&#39;. But you can visit &#39;/widgets&#39; page and &#39;ng2-app/&#39; page to enjoy your app working.</p><h3>Conclusion</h3><p>We&#39;ve looked at step by step process for building Rails Application and Angular2 app from scratch using own CLI tools. And we&#39;ve learned the Angular2 development workflow using &#39;ng serve&#39; and API proxy. And we have found how to integrate the Angualr2 app into Rails app by serving the assets via Rails routing, the controller, and the view. Finally, we deployed the app to Heroku for the worlds to enjoy.</p><p>The main advantage of the described process is the loose coupling of Rails and Angular2 apps, which ensure future-proof. If your team expands and you&#39;d want to create separate repositories for Rails and Anguar2 app, you only need to move ng2-app directory out of root directory and couple lines of configurations. And if you&#39;d like to add more Angular2 apps under the same umbrella, you can do that by typing &#39;ng new another-app&#39;.</p><p>Although I used Angular2 in this example, the same process can be applied to any JavaScript Single Page App using bundlers like webpack or jspm or build tools like Grunt.</p><p>You can download entire code from <a href="https://github.com/sungthecoder/rails_ng2">github</a> and view the working app <a href="https://rails-on-ng2.herokuapp.com/ng2-app">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f3ab380af62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/how-to-have-angular2-and-rails-coexist-peacefully-on-your-laptop-and-servers-2f3ab380af62">How to have Angular2 and Rails coexist peacefully on your laptop and servers</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ‘this’ keyword in JavaScript]]></title>
            <link>https://medium.com/sungthecoder/understanding-this-keyword-in-javascript-d3593d73605a?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3593d73605a</guid>
            <category><![CDATA[this]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Wed, 25 May 2016 21:23:42 GMT</pubDate>
            <atom:updated>2016-05-26T23:01:36.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKSUVtCQaHeX9m62_V2jEw.jpeg" /></figure><p>If you are coming to JavaScript world from classical OO languages like Java or C++, you’d be very happy to see ‘<strong><em>class</em></strong>’ and ‘<strong><em>this</em></strong>’ keyword in the language. But before you jump into writing Java looking JavaScript code, you should know that JavaScript class is not the same class you know before. The meaning of <strong><em>this</em></strong> is different in JavaScript.</p><p>First, let’s take a look at the code example:</p><pre>class Timer{<br>  constructor(second){<br>    this._second = second;<br>    document.getElementById(‘timer’).innerHTML = second;<br>  }</pre><pre>  _process(){<br>    this._second -= 1;<br>    document.getElementById(‘timer’).innerHTML = this._second;<br>    if (this._second &lt;= 0){<br>      this.stop();<br>    }<br>  }</pre><pre>  start() {<br>    this._interval = setInterval(function doSomething(){<br>      this._process();<br>    }, 1000);<br>  }</pre><pre>  stop() {<br>    clearInterval(this._interval);<br>  }<br>}</pre><pre>var t1 = new Timer(10);<br>t1.start();</pre><p>Above code declare Timer class. The Timer class has a constructor and 2 public methods, <em>start()</em> and <em>stop()</em>. The constructor accepts a number as a parameter.</p><p>And it creates a Timer object and call <em>start()</em> method. The <em>start()</em> method set interval to call <em>_process()</em> function every 1000 milliseconds.</p><p>But if you run this code, you will instead see nothing happening in the browser and ‘<strong>Uncaught Type Error: this_process is not a function</strong>’ in your development console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*jbAEHePeSD61ih5UcIJLIA.png" /></figure><p>This error is from start() method. The line with <strong><em>this</em>._process()</strong> is the problem. <strong><em>this</em></strong> object does not have<strong> _process</strong> method. If you use debugger, or add <strong>console.log(this);</strong> right above the <strong>this._process();</strong>, you would see that <strong><em>this</em></strong> is global object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58LdF5qmKyPZha2wOr9nyg.png" /><figcaption>console.log(this) shows Window object</figcaption></figure><p>Why is that happening? Should this be the Timer object? To understand this phenomenon, you need to understand how <strong><em>this</em></strong> works in JavaScript.</p><h4>How to determine the meaning of ‘<strong>this</strong>’</h4><p>Unlike classical OO languages, <strong><em>this</em></strong> does not mean object itself. <strong><em>this</em></strong> in JavaScript is more of call site. I’ll explain what the call site means later. When JavaScript sees this keyword, it asks these three questions to determine the value of this in the same order as below.</p><ol><li>Is the function called with <strong>new</strong> keyword?</li><li>Is the function called with <strong>explicit binding</strong>?</li><li>Is the function called with containing object (<strong>implicit binding</strong>)?</li><li>Then it is the default value: <strong>global</strong> or <strong>undefined</strong> in strict mode.</li></ol><p>Let’s take a look at each case.</p><h4>Default: Global Object or Undefined</h4><p>When a function is called standalone, <strong><em>this</em></strong> binds to global object.</p><pre>function whatIsThis(){<br>  console.log(<strong><em>this</em></strong>);<br>}</pre><pre>whatIsThis();</pre><p>The above code will show window object on console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZRWimMGEQdXrAiBwfV_qg.png" /><figcaption>this is global object</figcaption></figure><p>But if your code is running in strict mode, <strong><em>this</em></strong> will be undefined.</p><h4>Implicit Binding</h4><p>If you are calling a function as a method of an object, <strong><em>this</em></strong> will bind to the object that contains the function.</p><pre>function sayName(){<br>  console.log(<strong><em>this</em></strong>._name);<br>}</pre><pre>var foo = {<br>  _name: &quot;Foo&quot;,<br>  sayName: sayName<br>}</pre><pre>var bar = {<br>  _name: &quot;Bar&quot;,<br>  sayName: sayName<br>}</pre><pre>foo.<strong>sayName</strong>();<br>// Foo</pre><pre>bar.<strong>sayName</strong>();<br>// Bar</pre><pre><strong>sayName</strong>();<br>// undefined</pre><p>As seen on the code above, the value of <strong><em>this</em></strong> is dynamically determined. When sayName() function is called within <strong>foo</strong> object, <strong><em>this</em></strong> binds to <strong>foo</strong> object. But the value of <strong><em>this</em></strong> becomes <strong>bar</strong> object when the function is called within <strong>bar</strong> object. So the value of <strong><em>this </em></strong>depends on where it was called from. You can think this as a <em>call site</em>.</p><p>When sayName() is called without any object, <strong><em>this</em></strong> becomes global object (or undefined if it is strict mode).</p><h4>Explicit binding</h4><p>You can force the value of <strong><em>this</em></strong> with .<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call()</a> or .<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply()</a> function. Or you can create a function that always binds to a certain object with .<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind()</a> function. When you call a function with <strong>.call(thisObj)</strong> or <strong>.apply(thisObj)</strong>, the value of <strong><em>this</em></strong> inside of the function will be <strong>thisObj</strong>. Let’s take a look at the code:</p><pre>function sayName(){<br>  console.log(<strong><em>this</em></strong>._name);<br>}</pre><pre>var foo = {<br>  _name: &quot;Foo&quot;,<br>  sayName: sayName<br>}</pre><pre>var bar = {<br>  _name: &quot;Bar&quot;,<br>  sayName: sayName<br>}</pre><pre>sayName.<strong>call</strong>(bar);<br>// Bar</pre><pre>sayName.<strong>call</strong>(foo);<br>// Foo</pre><pre>foo.sayName.<strong>call</strong>(bar);<br>// Bar</pre><pre>bar.sayName.<strong>call</strong>(foo);<br>// Foo</pre><p>Note that in the last line of the code, even when <strong>sayName</strong> is called within <strong>bar</strong> object, .<strong>call(foo)</strong> override the value of this to be <strong>foo</strong>.</p><p>If you want to create a function that always bind <strong><em>this</em></strong> to a certain object, use <strong>.bind()</strong> function.</p><pre>function sayName(){<br> console.log(this._name);<br>}</pre><pre>var foo = {<br> _name: “Foo”,<br>}</pre><pre>var sayFoo = sayName.<strong>bind</strong>(foo);</pre><pre>var bar = {<br> _name: “Bar”,<br> sayName: sayName,<br> sayFoo: sayFoo<br>}</pre><pre>sayFoo();<br>// Foo</pre><pre>bar.sayFoo();<br>// Foo</pre><pre>sayFoo.call(bar);<br>// Foo</pre><pre>bar.sayName();<br>// Bar</pre><p><strong>sayFoo()</strong> function is newly created function based on sayName. But it was created with <strong>.bind()</strong> method. So <strong><em>this</em></strong> value in sayFoo will always be <strong>foo</strong> object.</p><p>When <strong>sayFoo</strong> is called within <strong>bar</strong> object, the value of <strong><em>this</em></strong> stays as <strong>foo</strong> object. Even when it is called with <strong>.call(bar)</strong> function, this still is <strong>foo</strong>.</p><h4>Function or Class with new keyword</h4><p>When a function is called with <strong>new</strong> keyword, it does following things:</p><ol><li>Creates an empty object {}</li><li>Binds <strong><em>this</em></strong> to the newly created empty object</li><li>Runs the function or constructor</li><li>Returns the newly created object</li></ol><p>Let’s look at the example of function and class definition.</p><pre>function Beer(alcohol) {<br>  this._happy = true;<br>  this._focus = false;<br>  this._alcoholContent = alcohol;<br>}</pre><p>or</p><pre>class Beer{<br>  constructor(alcohol) {<br>    this._happy = true;<br>    this._focus = false;<br>    this._alcoholContent = alcohol;<br>  }<br>}</pre><p>When you call the <strong>Beer</strong> function with new object like this:</p><pre>var beer = new Beer(5);</pre><p>It will (1)create an empty object, (2)fill the object with _happy, _focus, and _alcoholContent properties and (3)return the newly created object. The returned object will look like this:</p><pre>{<br>  _happy:          true,<br>  _focus:          false,<br>  _alcoholContent: 5<br>}</pre><h4>Back to our Timer problem</h4><pre>class Timer{<br>  /* ... omitted ... */</pre><pre>start() {<br>    <strong><em>this</em></strong>._interval = setInterval(function <strong>doSomething</strong>(){<br>      <strong><em>this</em></strong>._process();<br>    }, 1000);<br>  }</pre><pre>/* ... omitted ... */</pre><pre>var t = new Timer(10);<br>t.start();</pre><p>In the <strong>start()</strong> method, there are two <strong><em>this</em></strong> keywords. It looks like both <strong><em>this</em></strong> keywords are referring to the same Timer object, but they have different meaning.</p><p>When you call <strong>t.start()</strong>, the value of <strong><em>this</em></strong> becomes <strong>t</strong>. And the <strong>start()</strong> function will call <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval">setInterval()</a> with <strong>doSomething</strong> (1st argument) and 1000 millisecond (2nd argument). And the return value, intervalId, will be stored in <strong><em>this</em>._interval</strong> or <strong>t._interval</strong>.</p><p>One second later, when the <strong>doSomething()</strong> is called, the function is not bound to the <strong>t</strong> object anymore. You can ask the 3 questions to determine the value of <strong><em>this</em></strong>. (1) Is it called with <strong>new</strong> keyword? No. (2) Is the function explicitly bound to an object? No. (3) Is it called within a containing object? No. Answer to all these 3 questions are No. So the value of <strong><em>this</em></strong> becomes global (or undefined). And the global doesn’t have <strong>_process()</strong> method. That’s why we see the error message.</p><h4>Solution to the problem</h4><p>How can we solve the problem with <strong><em>this</em></strong> being dynamic? One of the solution is to create a function that binds <strong><em>this</em></strong> to <strong>t</strong> object. You can use <strong>.bind()</strong> function for that.</p><pre>start() {<br>    var boundFunction = function doSomething(){<br>      this._process();<br>    }.<strong>bind</strong>(this);</pre><pre>    <strong><em>this</em></strong>._interval = setInterval(boundFunction, 1000);<br>  }</pre><p>The boundFunction is a new function created based on <strong>doSomething()</strong> with <strong>.bind(this)</strong>. Within the <strong>boundFunction</strong>, the value of <strong><em>this</em></strong> will always be the same <strong><em>this</em></strong> as in <strong>start()</strong> function. So when you call</p><pre>t.start();</pre><p>The value of <strong><em>this</em></strong> is <strong>t</strong> inside of the <strong>start()</strong> function, and you force <strong><em>this</em></strong> inside boundFunction to be <strong>t</strong>. So whenever <strong>boundFunction</strong> is called, <strong><em>this</em></strong> will always refer to <strong>t</strong>.</p><h4>Conclusion (TL;DR;)</h4><p>JavaScript has different meaning of <strong><em>this</em></strong>. In classical Object Orient language like Java or C++, <strong><em>this</em></strong> means object itself. However, in JavaScript, <strong><em>this</em></strong> has closer meaning to call site (where the function was called from).</p><p>You can determine the meaning of <strong><em>this</em></strong> by asking these 3 questions:</p><ol><li>Is the function called with <strong>new</strong> keyword? Then <strong><em>this</em></strong> is newly created empty object</li><li>Is the function called with <strong>explicit binding</strong>? Then <strong><em>this</em></strong> is thisArg argument from <em>.call(thisArg)</em>, <em>.apply(thisArg)</em>, or <em>.bind(thisArg)</em></li><li>Is the function called within containing object? Then <strong><em>this</em></strong> is the containing object.</li><li>If all the answers are No, <strong><em>this</em></strong> is the default value: <strong>global</strong> or <strong>undefined</strong> in strict mode.</li></ol><p>And the corrected version of the Timer code is this:</p><pre>class Timer{<br>  constructor(second){<br>    this._second = second;<br>    document.getElementById(‘timer’).innerHTML = second;<br>  }</pre><pre>_process(){<br>    this._second -= 1;<br>    document.getElementById(‘timer’).innerHTML = this._second;<br>    if (this._second &lt;= 0){<br>      this.stop();<br>    }<br>  }</pre><pre>start() {<br>    this._interval = setInterval(function doSomething(){<br>      this._process();<br>    }<strong>.bind(this)</strong>, 1000);<br>  }</pre><pre>stop() {<br>    clearInterval(this._interval);<br>  }<br>}</pre><pre>var t1 = new Timer(10);<br>t1.start();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3593d73605a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/understanding-this-keyword-in-javascript-d3593d73605a">Understanding ‘this’ keyword in JavaScript</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making multiple AJAX calls and Deciphering $.when.apply($, array);]]></title>
            <link>https://medium.com/sungthecoder/making-multiple-ajax-calls-and-deciphering-when-apply-array-b35d1b4b1f50?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35d1b4b1f50</guid>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jquery]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Mon, 16 May 2016 23:52:49 GMT</pubDate>
            <atom:updated>2016-05-19T03:51:29.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJEmOYQWysJkRZ9eF4eV0w.jpeg" /></figure><p>I had a chance to help a FCC student with <a href="https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api">his project</a>. The main challenge of the project is about making multiple AJAX calls. The pseudo code for the project look like this:</p><ol><li>Make multiple AJAX calls to a server</li><li>Store the results in an array</li><li>Sort or group the array by status property.</li><li>Create DOMs and attach them to HTML page.</li></ol><p>The following code was what the student’s code looked like:</p><pre>var i,<br>    ids=[‘1’,’2&#39;,’3&#39;,…,’n’], <br>    results = [];</pre><pre>// 1. Make multiple AJAX calls to a Server<br>for (i=0; i &lt; ids.length; ++i){<br>  $.ajax(‘http://api.server.com/&#39;+id, {<br>    success: function(result) {<br>      // 2. Store the results in an array<br>      results.push(result);<br>    }<br>  });<br>}</pre><pre>// 3. Process the result array.<br>groupedResults = groupByStatus(results)</pre><pre>// 4. Create DOMs and attach them to HTML page.<br>buildDOMAndAttach(groupedResults);</pre><p>For the sake of the conversation, let’s assume that <em>groupByStatus()</em> and <em>buildDomAndAttach()</em> functions magically do what they are supposed to do.</p><p>At a first glance, this code snippet looks innocent and do what we would like to do. However, when we run the code, we will see nothing on the browser. That is because when we group the <em>results</em> and build DOM, the <em>results</em> array is empty.</p><p>Why is it empty? Because, <em>$.ajax</em> is asynchronous call. When the JavaScript engine runs the next line of code of $.ajax(…), it didn’t finish fetching data from the server. It simply put that request on a queue somewhere behind curtain and do it whenever it has time to do so. And when it finishes the request, it will tell us that it has finished and the data are ready.</p><p>Then how can we tell the JavaScript engine to do something with the result when the the request is done? We can make use of <strong>Promise</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*PLL5TzHKue4jEtXVsc5F-A.jpeg" /><figcaption>Gust pager: when the pager buzzes, please return to the host.</figcaption></figure><p>Promise is like a guest pager. When you go get a burger at a burger shop, you place an order and they give you a guest pager. You hold on to the pager and you can go to the next shop and take care of other errant until the page rings. When the page rings, you go back to the burger shop and pick up the foods.</p><p>The previous scenario can be written in JavaScript like this:</p><pre>// 1. Place a order for me!<br>var pager = placeAnOrder(“http://api.burger.shop/me&quot;);</pre><pre>pager.done(function(food){<br>  // 3. When the food is ready, eat!<br>  eat(food);<br>});</pre><pre>// 2. Take care of other errants<br>takeCareOfErrant();</pre><p>Note that the order of the action is not same as the sequence of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*QNn9bXnCjNVprKlH53z6HQ.jpeg" /><figcaption>Let’s wait for all the pages buzz</figcaption></figure><p>But, what if you and your friends placed separate orders, and you and your friends want to eat together when all the orders are ready? That’s when <em>jQuery.when()</em> function comes into play.</p><p><em>jQuery.when()</em> accepts list of promises. So the scenario with multiple orders can be written like this:</p><pre>var i,<br>    names=[‘me’, ‘friend1’, ‘friend2’],<br>    pager,<br>    pagers=[],<br>    foodTray=[];</pre><pre>// 1. Place orders for each person<br>for(i = 0; i &lt; names.length; ++i){<br>  pager = placeAnOrder(“http://api.burger.shope&quot; + names[i]);<br>  pager.done(function(food){<br>    // 3. when a order is ready, place the food on the tray<br>    foodTray.push(food);<br>  });</pre><pre>  // 2. Collect the pager in one collection<br>  pagers.push(pager);<br>}</pre><pre>// 4. when all the orders are ready, eat together!<br>$.when(pagers[0], pagers[1], pagers[2]).then(function(){<br>  eatTogether(foodTray);<br>});</pre><p>The above code will collect all the pagers from the order. When each order is completed, we will put the food on a tray. And $.when() function will ensure that we wait for all the pagers ring before we eat together.</p><p>However, there is a little problem. $.when() function accept lists of arguments, so we have to pass them like this:</p><pre>$.when(pagers[0], pagers[1], pagers[2]);</pre><p>This works in our case because we only have 3 pagers. But, what if we have hundreds of them? Or what if we don’t know how may at the time of writing code? We need a way to convert this pagers array into list of arguments. That’s where apply() function comes in handy.</p><pre>fun.apply(thisArgs, array);</pre><p>will call the function <em>fun()</em> with argument list from the array. And the first argument is the value of ‘<em>this</em>’ keyword inside of fun() function.</p><p>When we call <em>$.when()</em> function, ‘<em>this</em>’ keyword inside the function is implicitly bind to <em>jQuery</em> object. But when we call $.when.apply(), we have to explicitly bind ‘this’ keyword to something. And we know that the binding has to be with <em>jQuery</em> object, so we pass <em>jQuery</em> object, a.k.a., <em>$</em> as the first argument.</p><p>So the last line of the previous solution can be rewritten like this:</p><pre>$.when.apply($, pagers).then(…);</pre><p>By this point, I hope you figure that what need to be changed to correct the solution. With the knowledge of the <strong>promise</strong>, <strong><em>$.when()</em></strong> and <strong><em>apply()</em></strong> function, the solution are rewritten like this:</p><pre>var i,<br>    ids=[‘1’,’2&#39;,’3&#39;,…,’n’],<br>    results = [],<br>    deferred,<br>    deferreds = [];</pre><pre>// 1. Make multiple AJAX calls to a Server<br>for (i=0; i &lt; ids.length; ++i){<br>  deferred = $.ajax(‘http://api.server.com/&#39;+id, {<br>    success: function(result) {<br>    // 2. Store the results in an array<br>    results.push(result);<br>  }<br>  deferreds.push(deferred);<br>});</pre><pre>$.when.apply($, deferreds).then(function() {<br>  // 3. Process the result array.<br>  groupedResults = groupByStatus(results)<br>  // 4. Create DOMs and attach them to HTML page.<br>  buildDOMAndAttach(groupedResults);<br>});</pre><p>I hope this helps you understand how to make multiple ajax calls. Please leave a comment for other questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35d1b4b1f50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/making-multiple-ajax-calls-and-deciphering-when-apply-array-b35d1b4b1f50">Making multiple AJAX calls and Deciphering $.when.apply($, array);</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief history of JavaScript Modules]]></title>
            <link>https://medium.com/sungthecoder/javascript-module-module-loader-module-bundler-es6-module-confused-yet-6343510e7bde?source=rss-e7fcc9d942f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6343510e7bde</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[SungTheCoder]]></dc:creator>
            <pubDate>Thu, 12 May 2016 20:27:32 GMT</pubDate>
            <atom:updated>2017-01-02T03:57:24.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68FMiPIAUMmxaDexaJLesA.png" /><figcaption>Brick Modules and Dependencies</figcaption></figure><p>Are you new to JavaScript and confused about module, module loader and module bundler? Or you have been writing JavaScript code for a while, but can’t get a grip of the jargons about module? You heard about the jargons like CommonJS, AMD, Browserify, SystemJS, Webpack, JSPM, etc., but don’t understand why we need them?</p><p>I will try to explain what are they, and what problem they try to solve, and how they solve the problem.</p><h4>Example Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*oPUjUJwA7FamPbG48wh5TQ.png" /><figcaption>Successful application launch</figcaption></figure><p>In this post, I’ll use a simple web application to demonstrate the concept of module. The application displays the sum of array on the browser. This application consists of 4 functions and one <em>index.html</em> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*0Xvs9xTXSvRHbPMsZ79xeA.jpeg" /><figcaption>Dependency diagram of the functions</figcaption></figure><p>The main function calculate the sum of numbers in the array and display the answer to <em>span#answer</em>. The sum function has dependency on two functions: add and reduce. <em>Add</em> function does what it says it does; it adds two numbers. <em>Reduce</em> functions will iterate through array and call iteratee call back function.</p><p>Take a time to understand the code below. I will use the same functions again and again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bafdae9e24900df495d31d484bbb7ca/href">https://medium.com/media/0bafdae9e24900df495d31d484bbb7ca/href</a></iframe><p>Let’s look at how we can put these pieces together to build an app.</p><h3>Inline Script</h3><p>Inline script is when you add JavaScript code between <em>&lt;script&gt;&lt;/script&gt;</em> tag. This is how I started JavaScript. I believe most of JavaScript developer have done this at least once in their life time.</p><p>This is very good way to get started. There is no external files or dependency to worry about. But this is also perfect recipe for unmaintainable code because of following:</p><ul><li><strong>Lack of Code Reusability</strong>: If we need to add another page and need some of the functions from this page, we will have to <em>copy and paste</em> the code</li><li><strong>Lack of Dependency Resolution</strong>: You are responsible for having <em>add</em>, <em>reduce</em> and <em>sum</em> functions come before <em>main</em> part of the script.</li><li><strong>Pollution of global namespace</strong>: All the functions and variables will reside on global scope.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eb808db92c9dea7a0dd1c99b945f64b/href">https://medium.com/media/7eb808db92c9dea7a0dd1c99b945f64b/href</a></iframe><h3>Script tags</h3><p>This is natural transition from inline scripting. Now we divide the big chunk of JavaScript into smaller pieces and load them using <em>&lt;script src=”…”&gt;&lt;/script&gt; </em>tags.</p><p>By separating files into multiple JavaScript files, we can reuse the code. We no longer need to <em>copy and paste</em> code between different html pages. We simply need to <em>include</em> the file with script tags. Although this is better approach, this still has following problems.</p><ul><li><strong>Lack of Dependency Resolution</strong>: The order of the files are important. You are responsible for including <em>add.js</em>, <em>reduce.js</em> and <em>sum.js</em> files before <em>main.js</em> file.</li><li><strong>Pollution of global namespace</strong>: All the functions and variables are still in global scope.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b9fef6df1131107883123c5c609884a/href">https://medium.com/media/8b9fef6df1131107883123c5c609884a/href</a></iframe><h3>Module Object and IIFE(Module Pattern)</h3><p>By using module object and <a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression">Immediately-invoked function expression(IIFE)</a>, we can reduce global scope pollution. In this approach, we expose only one object to global scope. The single object contains all the methods and values we need in our application. In this example, we expose only <em>myApp</em> object to global scope. All the functions will be held onto <em>myApp</em> object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15a0f48f54220ffea85d246a18d330b5/href">https://medium.com/media/15a0f48f54220ffea85d246a18d330b5/href</a></iframe><p>Note that each file except <em>my-app.js</em> is now wrapped into IIFE format.</p><pre>(function(){ /*... your code goes here ...*/ })();</pre><p>By wrapping each file into IIFE, all the local variables stay within the the scope of the function. So all the variables in the functions will stay within the scope of the function without polluting the global scope.</p><p>We expose <em>add</em>, <em>reduce</em> and <em>sum</em> functions by attaching them to <em>myApp</em> object. And we access these functions by referring <em>myApp</em> objects like this:</p><pre>myApp.add(1,2);<br>myApp.sum([1,2,3,4]);<br>myApp.reduce(add, value);</pre><p>We can also pass <em>myApp</em> global object via IIFE parameter just like shown in ‘<em>main.js</em>’ file. By passing the object as parameter to IIFE, we can choose shorter alias for the object. And our code will be a little bit shorter.</p><pre>(function(obj){<br>  // obj is new veryLongNameOfGlobalObject<br>})(veryLongNameOfGloablObject);</pre><p>This is huge improvement compared to previous example. And most of popular JavaScript libraries such as jQuery use this pattern. It exposes one global object, $, and all the functions are under $ object.</p><p>Yet, this is not a perfect solution. This approach still suffers from the same problem as previous section.</p><ul><li><strong>Lack of Dependency Resolution</strong>: The order of the files are still important. <em>myApp.js</em> file must come before any other files. And <em>main.js</em> file must come after all other library files.</li><li><strong>Pollution of global namespace</strong>: Number of global variable is now 1, but is not zero yet.</li></ul><h4>CommonJS</h4><p>In 2009, there were discussions about bringing JavaScript to server side. Thus ServerJS was born. ServerJS later changed its name to CommonJS.</p><p>CommonJS is not a JavaScript library. It is a standardization organization. It is like ECMA or W3C. ECMA defines the language specification for JavaScript. W3C defines JavaScript web API, such as DOM or DOM events. The goal of CommonJS is to define common APIs for web server, desktop and command line applications.</p><p>CommonJS also defines APIs for module. Since there is no HTML page and no <em>&lt;script&gt;</em> tag on server application, it make sense to have some clear APIs for modules. Modules need to be exposed(<strong>export</strong>) to others for use and be accessible(<strong>import</strong>). Its module syntax for export looks like this:</p><pre>// add.js<br>module.exports = function add(a, b){<br>  return a+b;<br>}</pre><p>The above code is to define and export a module. This code is saved in <em>add.js</em> file.</p><p>To use or import <em>add</em> module, you need <em>require</em> function with filename or module name as parameter. The following syntax describes how to import a module to your code.</p><pre>var add = require(‘./add’);</pre><p>If you have written code on NodeJS, this syntax may look familiar. That’s because NodeJS implemented CommonJS style module API.</p><h4>Asynchronous Module Definition(AMD)</h4><p>The problem with CommonJs style module definition is that it is synchronous. When you call ‘<em>var add=require(‘add’);</em>’, the system will be on halt until the module is ready. This mean this line of code will freeze the browser while all the modules are being loaded. So this may not be the best way to define modules for browser side application.</p><p>To transfer module syntax from server usage to browser usage, CommonJS proposed several module formats, “Module/Transfer”. One of the proposals, “Module/Transfer/C” later become <a href="https://github.com/amdjs/amdjs-api/blob/master/AMD.md">Asynchronous Module Definition (AMD)</a>.</p><p>AMD has following format:</p><pre>define([‘add’, ‘reduce’], function(add, reduce){<br>  return function(){...};<br>});</pre><p>The <em>define</em> function(or keyword) takes list of dependencies and a callback function as arguments. The arguments for the callback function will be the same order of dependencies in the array. This is equivalent to importing modules. And the callback function returns a value, which is the value you export.</p><p>CommonJS and AMD solves the two remaining problems with module pattern: <strong>dependency resolution</strong> and <strong>pollution of global scope:</strong> We only need to take care of dependencies for each module or each file. And there is no pollution for global scope.</p><h4>RequireJS</h4><p>AMD can save us from the hell of script tags and global pollution in our browser application. Then, how can I use it? RequireJS is here to help us. RequireJS is a JavaScript <strong>module loader</strong>. It helps load modules asynchronously as needed.</p><p>Despite its name, its goal is not to support CommonJS ‘require’ syntax. With RequireJS, you can write AMD style module.</p><p>Before you write your own application, you will have to download ‘<em>require.js</em>’ file from <a href="http://requirejs.org/docs/start.html">RequireJS website</a>. The following code is the example application written with RequireJS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca707bf7ab8523fd709037ed8d2839a/href">https://medium.com/media/eca707bf7ab8523fd709037ed8d2839a/href</a></iframe><p>Notice that there is only one script tag in index.html file.</p><pre>&lt;script data-main=”main” src=”require.js”&gt;&lt;/script&gt;</pre><p>This tag loads ‘<em>require.js’</em> library to the page. And ‘<em>data-main</em>’ attribute tells RequireJS to where is the starting point of your application. By default, it assumes that all files have ‘<em>.js</em>’<em> </em>file extension. So it is ok to omit ‘<em>.js’</em> file extension. After RequireJS loads ‘<em>main.js’</em> file, it loads its dependencies and dependencies’ dependencies, etc. The browser’s developer tool shows all the files are loaded in following order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGkqF-sTQA4SW8GpAvg1bg.png" /></figure><p>Browser loaded ‘<em>index.html</em>’ and ‘<em>index.html</em>’ loaded ‘<em>require.js</em>’. Rest of the files and dependencies are all taken care by ‘<em>require.js</em>’.</p><p>RequireJS and AMD solve all the problems we had before. However, it creates other slightly less serious problems.</p><ul><li>AMD syntax is too verbose. Since everything is wrapped in ‘define’ function, there are extra indentation for our code. With a small files, it is not much problem, but for a large code base, it can be mentally taxing.</li><li>List of dependencies in the array must match the list of arguments in the function. If there are many dependencies, it can be hard to maintain the order of the dependencies. If you have dozens of dependencies in your module, and later if you had to remove one in the middle, it can be difficult to find matching module and argument.</li><li>With current browsers(HTTP 1.1), loading many small files can degrade the performance.</li></ul><h4>Browserify</h4><p>Because of these reasons, some people want to use CommonJS syntax, instead. But CommonJS syntax is for server and synchronous, right? Browserify is here to rescue you! With Browserify, you can use CommonJS module in browser application. Browserify is a <strong>module bundler</strong>. Browserify traverse the dependency tree of your codes and bundle them up in a single file.</p><p>Unlike RequireJS, Browserify is a command line tool. You will need NodeJS and NPM to install it. Once you have nodeJS installed on your system, type the following command.</p><pre>npm install -g browserify</pre><p>Let’s take a look at our example application in CommonJS syntax.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/315f3535aa26b57988a30f65d7cce3a1/href">https://medium.com/media/315f3535aa26b57988a30f65d7cce3a1/href</a></iframe><p>You may notice that in our ‘<em>index.html</em>’ file, the script tag loads <em>bundle.js</em>. Where is the <em>bundle.js</em> file? Browserify generate the file for us, once you execute following command.</p><pre>$ browserify main.js -o bundle.js</pre><p>Browserify parses <em>main.js</em> for require() function calls and traverses dependency tree of your projects. Then it bundle them up in a single file.</p><p>Here’s what ‘<em>bundle.js</em>’ file look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9379cb145b565b560b1ea0588ca054be/href">https://medium.com/media/9379cb145b565b560b1ea0588ca054be/href</a></iframe><p>You don’t have to understand this bundle file line by line. But it is just worth note that all the familiar codes, main file and all of its dependencies, are included in this file.</p><h4>UMD — Just to make you more confused</h4><p>Now we’ve leaned about Global Object, CommonJS and AMD style modules. And there are libraries that can help us use either CommonJS or AMD. But what if you are writing a module and deploy to the wild internet? Which module style do you need to write?</p><p>Writing three different module types, i.e., global module object, CommonJS and AMD is an option. But then you will have to maintain three different files. And users will have to identify the type of the module they are downloading.</p><p>Universal Module Definition(UMD) is to solve this particular problem. Under the hood, UMD is a series of if/else statements to identify module style that current environment supports.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17d5bf1d9e0d3e2e8750cebff22136b2/href">https://medium.com/media/17d5bf1d9e0d3e2e8750cebff22136b2/href</a></iframe><h4>ES6 module syntax</h4><p>JavaScript global module object, CommonJS, AMD and UMD. There are too many options. Now you may ask, what should I use for my next project? The answer is none of them.</p><p>JavaScript didn’t have module system built into the language. That’s the reason we have so many different way of importing and exporting modules. But that has recently changed. With ES6 language spec, module is part of JavaScript. So the answer to the question is you need to use ES6 module syntax if you want your project to be future-proof.</p><p>ES6 uses ‘<em>import</em>’ and ‘<em>export</em>’ keywords to import and export modules. Here’s the example application written in ES6 modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/430d87f0b737b0c2fd6de963d09b33f7/href">https://medium.com/media/430d87f0b737b0c2fd6de963d09b33f7/href</a></iframe><p>There are many catch phrases about ES6 module: ES6 module syntax is concise. ES6 module will rule the JavaScript world. It is the future. But unfortunately, there is one problem. Browsers are not ready for this new syntax. At the moment of writing, only Chrome browser supports <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a> statement. Even when most of browsers support ‘<em>import</em>’ and ‘<em>export</em>’, if your application has to support older browsers, you may run into a problem.</p><p>Fortunately, there are tools available. These tools allow us to use ES6 module syntax today.</p><h4>Webpack</h4><p>Webpack is a <strong>module bundler</strong>. Just like Browserify, it traverses dependency tree and bundles up into a single or more files. If it is the same as Browserify, why would we need yet another module bundler? Webpack can handle CommonJS, AMD and ES6 modules. And Webpack comes with more flexibility and cool features like:</p><ul><li><strong>Code Split</strong>: When you have multiple apps sharing same modules. Webpack can bundle your code into two or more files. For example, if you have two apps, app1 and app2, and both shares many modules. With Browserify, you would have app1.js and app2.js. And both contain all the dependency modules. But with Webpack, you can create app1.js, app2.js, and shared-lib.js. Yes, you will have to load 2 files from html page. But with hashed filename, browser cache and CDN, it can reduce initial loading time.</li><li><strong>Loader:</strong> With custom loaders, you can load any file into your source. You can use ‘reuiqre()’ syntax to load not just JavaScript files, but also css, CoffeeScript, Sass, Less, HTML for template, images, etc.</li><li><strong>Plugin:</strong> Webpack plugins manipulate your bundles before it is written into files. There are many community built plugins. For example, there are bundle for adding banners to bundled code, adding source map and splitting a bundle into chunks, and more.</li></ul><p><em>WebpackDevServer</em> is development server that automatically bundles your source code and refresh browser whenever source code changes detected. It will expedite your development process by providing instant feedback of your code.</p><p>Let’s take a look how we can build the example application with Webpack. Webpack requires a little bit of bootstrapping and configuration.</p><p>Since Webpack is JavaScript command line tool, you will need NodeJS and NPM installed. Once you have NPM installed, initialize project.</p><pre>$ mkdir project; cd project<br>$ npm init -y<br>$ npm install -D webpack webpack-dev-server</pre><p>You need a configuration file for webpack. At a bare minimum, you will need <em>entry</em> and <em>output</em> field for your configuration. Save following content in <em>webpack.config.js</em> file.</p><pre>module.exports = {<br>   entry: ‘./app/main.js’,<br>   output: {<br>       filename: ‘bundle.js’<br>   }<br>}</pre><p>And open your ‘<em>package.json</em>’ file and add following lines under ‘script’ field.</p><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;webpack-dev-server -progress -colors&quot;,<br>    &quot;build&quot;: &quot;webpack&quot;<br> },</pre><p>Now add all your JavaScript modules under ‘<em>project/app</em>’ directory and ‘<em>index.html</em>’ under ‘<em>project</em>’ directory .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a4dbfa6c7189fdb740ac231bd428739/href">https://medium.com/media/3a4dbfa6c7189fdb740ac231bd428739/href</a></iframe><p>Note that ‘<em>add.js</em>’ and ‘<em>reduce.js</em>’ is written in CommonJS style, while ‘<em>sum.js</em>’ is written in AMD. Webpack, by default, can handle CommonJS and AMD. If you have ES6 modules, you will have to install and configure ‘babel loader’ for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*mxULJDkVDpCbQDAnB7y1vg.png" /><figcaption>webpack dev server in action</figcaption></figure><p>Once you have all the files ready, you can run your application.</p><pre>$ npm start</pre><p>And open your browser and point url to <a href="http://localhost:8080/webpack-dev-server/">http://localhost:8080/webpack-dev-server/</a>.</p><p>At this point, you can open up your favorite editor and edit your code. As you save the file, the browser will automatically refresh to show the result of the change.</p><p>One thing you may notice is that you will not find ‘<em>dist/bundle.js</em>’ file. That’s because Wepback Dev Server creates bundle, but it does not write into the file system. It serves the bundled code just out of memory.</p><p>For deployment, You may want to create a bundled file. You can create ‘<em>bundle.js</em>’ file with following command.</p><pre>$ npm run build</pre><p>If you are interested in learning more about Webpack, visit <a href="https://webpack.github.io/docs/">Webpack document page</a>.</p><h4>Rollup (May 2015)</h4><p>Have you ever include a large JavaScript library only to use a few of its functions? Rollup is another JavaScript ES6 module bundler. Unlike Browserify or Webpack, rollup only includes the codes that are used in your project. If you have a large module with many functions yet you only need a few of them, rollup will include only the functions you need into the bundle. This can reduce the size of bundle significantly.</p><p>Rollup can be used as a command line tool. Once you have NodeJS and NPM, install rollup with following command.</p><pre>$ npm install -g rollup</pre><p>Rollup can work with any type of module style. But, ES6 module style is recommended to take advantage of the tree-shaking feature. The following code is the example application written in ES6.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7769359394442f5cc7b65837e5d909/href">https://medium.com/media/3a7769359394442f5cc7b65837e5d909/href</a></iframe><p>Note that I introduced another function, ‘<em>sub()</em>’, in <em>add</em> module. But this function is not used in anywhere in the application.</p><p>Let’s bundle this code with rollup.</p><pre>$ rollup main.js -o bundle.js</pre><p>This will generate ‘<em>bundle.js</em>’ file like following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab9e940898981a6388a5641736db951b/href">https://medium.com/media/ab9e940898981a6388a5641736db951b/href</a></iframe><p>Note that ‘<em>sub()</em>’ function is not included in this bundle file.</p><h4>SystemJS</h4><p>SystemJS is a universal module loader. It loads the module dynamically on browser or NodeJS. And it supports CommonJS, AMD, global object and ES6 modules. With plugins, it can load not only JavaScripts, but CoffeeScript and TypeScript.</p><p>Another advantage of SystemJS is that it is built on top of ES6 module Loader polyfill. So its syntax and API will most likely be part of the language in the future. It will make your code more future-proof.</p><p>To import a module asynchronously with SystemJS, you can use following syntax</p><pre>System.import(‘module-name’);</pre><p>And you can configure the behavior of SystemJS with configuration API.</p><pre>System.config({<br>  transplier: ‘babel’,<br>  baseURL: ‘/app’<br>});</pre><p>The above configuration will let SystemJS use babel as transplier for ES6 modules and load modules from ‘<em>/app’</em> directory.</p><p>As modern JavaScript application become bigger and more complicated, so does development workflow. So we need more than just module loader. We would have to find development server, module bundler for production and a package manager for third party modules.</p><h4>JSPM</h4><p>JSPM is swiss army knife of JavaScript development tool. JSPM is a (1)package manager, (2)module loader and (3)module bundler.</p><p>Modern JavaScript development rarely ends up with your own modules. Almost always, you will need third party modules.</p><p>With JSPM, you can install third pary modules from NPM or Github using the followin command:</p><pre>jspm install npm:package-name <em>or</em> github:package/name</pre><p>This will download the package from ‘npm’ or ‘github’ and install it on ‘<em>jspm_packages’</em> directory.</p><p>While in development mode, you can use ‘<em>jspm-server</em>’. Just like Webpack Dev Sever, it detects the code change and reloads browser to show the changes. Unlike Webpack Dev Server, jspm-server make use of SystemJS module loader. So it doesn’t read all the files to bundle them every time it detects changes in a file. It just loads the modules that are required for the page you are working on.</p><p>When it comes to deployment, you would want to bundle your codes. JSPM comes with bundler. You can bundle your code with</p><pre>jspm bundle main.js bundle.js</pre><p>Under the hood, JSPM uses rollup for its bundler.</p><h4>Conclusion</h4><p>I hope this give you enough information for you to understand vocabularies about JavaScript modules. Now you may ask, what should I use for the next project? Unfortunately, I can’t answer that question. Now you have power to do your own research. I hope that it will be much easier for you to understand documents and articles about the tools I mentioned.</p><p>You can find all the code example in <a href="https://github.com/sungthecoder/js-modules-examples">this Github repository</a>. If you have any questions, please leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6343510e7bde" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sungthecoder/javascript-module-module-loader-module-bundler-es6-module-confused-yet-6343510e7bde">Brief history of JavaScript Modules</a> was originally published in <a href="https://medium.com/sungthecoder">sungthecoder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>