Thursday, December 7, 2017

Map, Filter and Reduce In Javascript

map creates a new array by transforming every element in an array, individually.
filter creates a new array by removing elements that don't belong.
reduce, on the other hand, takes all of the elements in an array, and reduces them into a single value.

Suppose we have an app that maintains an array of your tasks for the day. Each task is an object, each with a name and duration property:
// Durations are in minutes
 
var tasks = [ 
  { 
    'name'     : 'Write for Envato Tuts+', 
    'duration' : 120 
  }, 
  { 
    'name'     : 'Work out', 
    'duration' : 60 
  }, 
  { 
    'name'     : 'Procrastinate on Duolingo', 
    'duration' : 240 
  } 
];

map in Practice

Let's say we want to create a new array with just the name of each task, so we can take a look at everything we've gotten done today.

Using map, we can write:
var task_names = tasks.map(function (task, index, array) { 
    return task.name; 
});

// Using ES6 arrow functions
 var task_names = tasks.map((task) => task.name );

filter in Practice

The next of our array operations is filter. It takes an array, and filters out unwanted elements. Let's revisit our task example. Instead of pulling out the names of each task, let's say I want to get a list of just the tasks that took me two hours or more to get done.

Using filter, we can write:
var difficult_tasks = tasks.filter(function (task) {
    return task.duration >= 120;
});
 
// Using ES6 arrow functions
var difficult_tasks = tasks.filter((task) => task.duration >= 120 );

reduce in Practice

Let's turn back to our tasks example. What If we wanted to know the total amount of time we spent working today?

With reduce, that becomes:
var total_time = tasks.reduce(function (previous, current) {
    return previous + current.duration;
}, 0);
 
// Using ES6 arrow functions
var total_time = tasks.reduce((previous, current) previous + current.duration );

In this tutorial, you've learned how map, filter, and reduce work; how to use them; and roughly how they're implemented.

For detailed explanation, visit How to Use Map, Filter, & Reduce in JavaScript

Thursday, November 23, 2017

Understanding Three Cases of Components Communication in Vue 2.0

The way components communicate, in Vue 2.0, is through props and custom events. And with Vue 2.0 release, it has actually gotten simpler. So, in this article, I’d like to show you the different cases in which components communicate, and how to handle each one properly.

Three cases of components communication:
1. From parent to direct children, no custom events required; just use props.
2. From a child to its direct parent, use $emit(eventName) in children and the directive v-on:event-name in the parent.
3. Non Parent-Child communication i.e global component communication (from any component to any component), use the global event bus. Or use Vuex for more complex cases.

1. Parent-Child communication

It's called parent-child communication because they are directly related to each other. They inevitably need to communicate to one another: the parent may need to pass data down to the child, and the child may need to inform the parent of something that happened in the child.

In Vue, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events.

Pssing data with props
Data can be passed down to child components using props. A prop is a custom attribute for passing information from parent components. A child component needs to explicitly declare the props it expects to receive using the props option:
 <template>
  <div class="message">
    {{ message }}
  </div>
 </template>

 <script>
 export default {
   name: "child",
   props: ['message'] 
 }
 </script>
Then we can pass a plain string to child component from parent like so:
 <child message="hello!"></child>

2. Child-Parent Communication

We have learned that the parent can pass data down to the child using props, but how do we communicate back to the parent when something happens? This is where Vue's custom event system comes in.

To accomplish this kind of communication, you have to do two things:
1. First, Fire an event from the child component using $emit(eventName, [data]).
2. Listen to it on the parent using the v-on:event-name directly in the template where the child component is used.

Here’s a quick example:
Let’s say you’ve built your own custom dropdown component that contains a bunch of options which you pass from the parent. When an option is selected in that dropdown, it should emit an event to its parent, so it can do its stuff.

Here’s what happens when an option is selected in Dropdown.vue:
data () {
 return {
   selectedOption: null
 }
},
methods: {
  selected () {
    // assume 'this.selectedOption' is defined in the data object
    this.$emit('option-select', this.selectedOption)
  }
}
Now in the parent component — let’s call it NavBar.vue — we’ll have something like this (note that I’m using the shorthand for v-on which is @):
 <template>
  <div class="nav-bar">
    <!-- other elements -->
    <dropdown
      :options="someOptions"
      @option-select="onOptionSelect"
    ></dropdown>
  </div>
 </template>

  <script>
  export default {
    methods: {
      onOptionSelect (option) {
      // handle it here
      }
    }
  }
 </script>

3. Non Parent-Child communication

Sometimes two components may need to communicate with one-another but they are not parent/child to each other. In other words, global component communication.

You need to handle all the communications through event hub (or some call it event bus). In its simplest definition, it's an empty Vue instance that you use globally to fire and listen for events anywhere you want in the component's tree.

As I just mentioned, this eventHub is an empty Vue instance which you’d create like this:
 //empty Vue instance 
 var eventHub = new Vue()
This needs to be globally accessible
For everything to work correctly, you need to make sure that this eventHub is accessible globally. And this depends on how your application is structured.

If you’re building a simple non-modular app, you can attach that instance to the browser’s window object.

However, for module-based applications that use bundling tools like Webpack or Browserify, you can do that by exporting that instance from a certain file and then import it wherever you need it.
 // src/shared/EventHub.js

 import Vue from 'vue'
 export default new Vue()
Now in other components, you would import it like this:
 import eventHub from 'src/shared/EventHub'
Let’s imagine that we want to pass an event from component-A to component-B. To do that, we first need to emit that event from component-A:
 import eventHub from 'src/shared/EventHub'

// …

methods: {
  doSomething () {
    eventHub.$emit('id-selected', 1)
  }
}
Now, in component-B, you would listen to it like this:
 import eventHub from 'src/shared/EventHub'

 // …

 mounted () {
 // in component B's created hook  
 eventHub.$on('id-selected', (id) => {
     // handle it however you want.
   })
 }

As simple as that! The great thing about this approach is that you're no longer concerned about the components tree structure. In other words, events can be emitted from any component and handled by any other component regardless of their relationship.

In more complex cases, you should consider to use Vuex.

Sources:
Understanding Components Communication in Vue 2.0
Vue.js Components

Wednesday, October 25, 2017

How To Add Custom Helpers on Handlebars?

You can extend handlebars with your own custom helpers. This allows you to create complex logic using handlebar’s expression system. There are 2 kinds of helpers, a function helper and a block helper. The difference is that one is meant for a single expression and the other uses a block expression.


Custom Function Helpers
Creating function helpers is relatively easy. To create one, we have to register it using the registerHelper() method. It takes the name of the helper and the helper function as arguments. Handlebars.js takes whatever is returned from the helper function and writes it out to the template, so be sure to always return a string from your custom helpers.

To write an expression helper function to output a formatted phone number, you could define the following helper:
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
  phoneNumber = phoneNumber.toString();
  return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
});
You would use the formatPhoneNumber helper in a template like this:
{{formatPhoneNumber phoneNumber}}

Custom Block Helpers
Custom block helpers are also registered with the Handlebars.registerHelper method. When a helper is used with a block, Handlebars will pass the contents of the block compiled into a function to the helper.

Here's an example block helper that compare the option with a value, letting the contents know whether a value is equal to option. If the option is an equal to a value, helper just returns the 'selected' attribute else return empty string. This helper is useful to add a 'selected' attribute conditionally on any of the option elements.
Handlebars.registerHelper("selected", function(option, value) {
 if (option === value) {
        return 'selected';
    } else {
        return '';
    }
});

You would use the selected helper in a template like this:
<select name="countries" >
 <option  value="{{code}}" {{selected code "46" }>{{country_name}}({{code}})</option>
</select>
If the country code is equal to 46 i.e Sweden, the option will be selected.

Ref: Custom Helpers – Handlebars.js Tutorial

Friday, September 29, 2017

How To Install and Configure Homestead For Laravel 5 and OSX?

Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!

Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 7.1, MySQL, PostgreSQL, Redis, Memcached, Node, and all of the other goodies you need to develop amazing Laravel applications.

STEP 1: DOWNLOADING FILES
The first step is getting the required software for Homestead. Before launching your Homestead environment, you must install VirtualBox, (VMWare, or Parallels) as well as Vagrant. I used VirtualBox and as it is free, I am pretty sure most of you guys will be using it too.

STEP 2: INSTALLING VAGRANT HOMESTEAD BOX
Once VirtualBox / VMware and Vagrant have been installed, you should add the laravel/homestead box to your Vagrant installation using the following command in your terminal. It will take a few minutes to download the box, depending on your Internet connection speed:
 vagrant box add laravel/homestead

STEP 3: INSTALLING LARAVEL HOMESTEAD
You may install Homestead by simply cloning the repository. Consider cloning the repository into a Homestead folder within your "home" directory, as the Homestead box will serve as the host to all of your Laravel projects:
 cd ~
 git clone https://github.com/laravel/homestead.git Homestead
Once you have cloned the Homestead repository, run the bash init.sh command from the Homestead directory to create the Homestead.yaml configuration file. The Homestead.yaml file will be placed in the Homestead directory:
 cd Homestead
 bash init.sh

STEP 4: CONFIGURING THE LARAVEL HOMESTEAD
Rest of the configuration is easy. The homstead.yaml is already configured for a default app.

Setting Your Provider
The provider key in your Homestead.yaml file indicates which Vagrant provider should be used: virtualbox, vmware_fusion, vmware_workstation, or parallels. You may set this to the provider you prefer. I recommend virtualbox.
  provider: virtualbox
Configuring Shared Folders/ Folder Mapping
Folder mapping means that your Guest OS and Host OS will share a common folder where you can keep your laravel files. Laravel Homestead configures a default folder in the home directory of the Host OS.The folders property of the Homestead.yaml file lists all of the folders you wish to share with your Homestead environment. As files within these folders are changed, they will be kept in sync between your local machine and the Homestead environment. You may configure as many shared folders as necessary:
folders:
    - map: ~/Code
      to: /home/vagrant/Code
Sites
Sites is a configuration array for Nginx. By default configuration, you will have a “homestead.app” pseudo-domain which will point to a folder inside the “shared folder”. Any php code inside that folder will get executed when you will go to homestead.app inside your browser. You should set it to the “public” folder of your laravel app. Again, you may add as many sites to your Homestead environment as necessary. Homestead can serve as a convenient, virtualized environment for every Laravel project you are working on:

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public

If you change the sites property after provisioning the Homestead box, you should re-run vagrant reload --provision to update the Nginx configuration on the virtual machine.
 vagrant reload --provision
Note: It’s this particular step that tends to confuse most Homestead beginners, so pay close attention to the following description. The folders object’s map attribute identifies the location in which your Laravel project will be located. The default value is ~/Code, meaning Homestead expects your project to reside in a directory named Code found in your home directory. You’re free to change this to any location you please. The folders object’s to attribute identifies the location on the virtual machine that will mirror the contents of the directory defined by the map key, thereby making the contents of your local directory available to the virtual machine.
The sites object’s map attribute defines the domain name used to access the Laravel application via the browser. Finally, the sites object’s to attribute defines the Laravel project’s root web directory, which is /public by default.


If this explanation is clear as mud, let’s clarify with an example. Begin by setting the folders object’s map attribute to any path you please, likely somewhere within the directory where you tend to manage your various software projects. For instance, mine homestead.yaml is currently set like this:
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/development/projects
      to: /home/vagrant/projects

sites:
    - map: laravel.dev
      to: /home/vagrant/projects/laravel/public

    - map: homestead.app
      to: /home/vagrant/projects/tutorials/laravel-basics/public  

databases:
    - homestead

Here is the screen dump of my Folder Structure


STEP 5: CONFIGURING THE HOST FILE
You must add the "domains" for your Nginx sites to the hosts file on your machine. The hosts file will redirect requests for your Homestead sites into your Homestead machine. On Mac and Linux, this file is located at private/etc/hosts. Open the hosts file with administrative access
  sudo nano /private/etc/hosts
The lines you add to this file will look like the following. You can add it anywhere but for ease, add it at the bottom of the file as below.
192.168.10.10   laravel.dev
192.168.10.10   homestead.app
Make sure the IP address listed is the one set in your Homestead.yaml file.

After adding above lines to the file Press cltr + o, then Enter, then cltr+x
Here is the screenshot of my host file:

STEP 6: RISE AND SHINE HOMESTEAD
Open terminal and navigate to Homestead directory and run the following vagrant up command. Vagrant will boot the virtual machine and automatically configure your shared folders and Nginx sites.
  Anup:~ anup$ cd ~/Homestead
  Anup:Homestead anup$ vagrant up
You will have your Homestead running in no time. Now go to homestead.app in your browser and be ready to get an error. Most probably “No input File Found”. It is because we don’t have laravel app’s “public” folder yet. We will install laravel in the next step.

STEP 7: INSTALL COMPOSER AND LARAVEL
Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.
Installing Composer Run this in your terminal to get the latest Composer version:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
Make composer globally accessible
After running the installer, you can run this to move composer.phar to a directory that is in your path:
mv composer.phar /usr/local/bin/composer
Now just run composer in order to run Composer instead of php composer.phar
Via Laravel Installer
After the Composer is installed successfully, download the Laravel installer using Composer:
 composer global require "laravel/installer"
Make sure to place the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system. Open .bashrc file to add required $PATH as below:
  Anup:~ anup$ nano ~/.bashrc
Add the export PATH="$PATH:$HOME/.config/composer/vendor/bin" as below:

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel's dependencies already installed.

To install Laravel, we need to go the directory we have specified on STEP 4 (i.e. sites section of homestead.yaml) as below
Anup:~ anup$ cd development/projects/tutorials/laravel-basics/
Anup:laravel-basics anup$ laravel new
It will install laravel in the laravel-basics folder. Don't forget to create .env file on root directory(i.e. remove .example extension from .env.example). Otherwise, you will get error.

My Laravel project looks like below:

STEP 8: SSH’ing INTO YOUR MACHINE
Go the the Homestead directory, run vagrant up and vagrant ssh.
 Anup:~ anup$ cd ~/Homestead
 Anup:Homestead anup$ vagrant up

After vagrant is up, then you can ssh into it as below.
 Anup:Homestead anup$ vagrant ssh
 vagrant@homestead:~$ 
Go the respective project as below and run composer install to complete the Laravel installation process.
vagrant@homestead:~$ cd projects/tutorials/laravel-basics/
vagrant@homestead:~/projects/tutorials/laravel-basics$ composer install
vagrant@homestead:~/projects/tutorials/laravel-basics$ php artisan key:generate
Your Homestead virtual machine is up and running! Open a browser and navigate to the URL http://homestead.app and you should see

You may encounter errors and problems while following the above steps but everyone do. Homestead is very easy to install and configure and after a few minutes of playing around the problems, you will be able to fix it. Let me know in the comments, if I am missing anything in the article or if you are stuck with laravel homestead.

Sources :
Laravel Installation
Install Laravel Homestead on Windows Extremely Easily
Installing and Configuring Homestead 2.0 for Laravel 5

Wednesday, September 27, 2017

How to Upgrade to PHP 7 or 7.1 on macOS?

Usually, with a fresh version of macOS Sierra, you get a PHP 5.6 installed.

Download and Install to PHP 7.0 or 7.1
You’ve got two options: brew or curl install. I am showing how to upgrade to PHP version 7.0 or 7.1 using curl method.

Open Terminal and run…
curl -s http://php-osx.liip.ch/install.sh | bash -s 7.0
or for 7.1
curl -s http://php-osx.liip.ch/install.sh | bash -s 7.1

If the output of php -v still doesn't echoes the version 7, simply type following command to update your path, it should do the magic, as stated on php-osx.liip.ch website
export PATH=/usr/local/php5/bin:$PATH

Source: How to upgrade your version of PHP to 7.0 on macOS Sierra

Monday, September 11, 2017

How to Validate and Submit Form Using VueJs and PHP?

Client-side validation using JavaScript enhances user experience by giving feedback immediately to the user rather than having them complete a round-trip through the server. Before we begin, you must understand that this type of data input validation is no substitute for server-side validation. Without server-side validation, you are trusting the user and whatever tools they are using to make sure input is valid. Client-side validation with Vue.js (or any other JavaScript library/framework) should be used in addition to, not instead of it.

I'll also mention that many modern browsers have client-side validation built-in by using HTML attributes such as (but not limited to) required and maxlength="10". However, not all browsers support this and all of them behave differently. Let’s look at how to build our own form validation using Vue.js so it behaves the same in all modern browsers.

Scenario
We want to build a form with 4 inputs:
• Name
• Number between 1 and 10
• Email
• Message

All inputs are required. The number input should only allow numbers between 1 and 10 & email input should have a valid format.

Setup
Start with a basic HTML file with the Bootstrap 3 stylesheet and Vue.js.
<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8">
    <title>Form Validation</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
</body>
</html>
Our form will go in the content area. Just to get a prettier layout, we’ll put it inside a single col, inside a single row, inside a single container. Each of these elements have classes that position them nicely.
<!div class="container">
  <!div class="row justify-content-center">
    <!div class="col-md-6">
      <!form>
       <!!-- form elements go here -->
      <!/form>
    <!/div><!!-- /col -->
  <!/div><!!-- /row -->
<!/div><!!-- /container -->
Now, our 4 input elements and submit button will go inside the form. Bootstrap provides validation classes. Let’s add those as well.
  <div class="form-group">
      <label class="control-label" for="name">Name </label>
      <input id="name" name="name" class="form-control" type="text" v-model="name">
      <span id="helpBlock" class="help-block">This field is required. </span>
    </div>
    
    <div class="form-group">
      <label class="control-label" for="number">Enter a number between 1 and 10 </label>
      <input id="number" name="number" class="form-control" type="text" v-model="number">
      <span id="helpBlock" class="help-block">Make sure this is a number between 1 and 10. </span>
    </div>

    <div class="form-group">
      <label class="control-label" for="name"Email</label>
      <input id="email" name="email" class="form-control" type="text" v-model="email">
      <span id="helpBlock" class="help-block">Email is invalid. </span>
    </div>

    <div class="form-group">
      <label class="control-label" for="message">Enter a Message </label>
      <textarea  name="message" class="form-control" type="text" v-model="message"> </textarea>
      <span id="helpBlock" class="help-block">This field is required. </span>
    </div>                 
    
    <button class="btn btn-primary">Submit </button>

Right now, the feedback elements will always be displayed. Later, we'll make sure they’re only shown if validation fails.

Building the Vue App
With the HTML in place, now we'll jump into main.js and start coding the logic for our form.
var form = new Vue({
  el: '#form',
  data: {
    name: '',
    email: '',
    message: '',
    number: '',
    attemptSubmit: false,
    postStatus: false
  },
  computed: {
    missingName: function () {},
    wrongNumber: function () {},
    missingEmail: function () {},
    missingMessage: function () {}
  },
  methods: {
    isNumeric: function () {},
    isEmail: function () {},
    validateForm: function () {},
    onSubmit () {}
  },
});


In our data object, there are 6 variables:
1. name — Will hold the value of the name input
2. email — Will hold the value of the email input
3. message — Will hold the value of the message input
4. number — Will hold the value of the number input
5. attemptSubmit — A boolean that indicates whether the user has attempted to submit the form. We can use this to hide validation warnings until after the user has tried to submit the form.
6. postStatus - A boolean that indicates whether the form has been submitted. We can use this to hide the form after the submission.

There are also a 4 computed variables here:
1. missingName — Will return true if name is empty
2. wrongNumber — Will return true if number is not between 1 and 10
3. missingEmail — Will return true if email is empty or invalid
4. missingMessage — Will return true if message is empty

Finally, there are a 4 methods:
1. isNumeric — A utility function that checks to see if an input is a number
2. isEmail — A utility function that checks to see if an input has valid email
3. validateForm — The main function that will be called when trying to submit
4. onSubmit - If the validation is passed, that will be called

I mentioned above that there are 4 variables that hold the value of the inputs. We can wire those up with Vue models. Back in the HTML…
  <input id="name" name="name" class="form-control" type="text" v-model="name">
  <input id="number" name="number" class="form-control" type="text" v-model="number">
  <input id="email" name="email" class="form-control" type="text" v-model="email">
  <textarea  name="message" class="form-control" type="text" v-model="message"></textarea>
With our models wired up, we can use the computed variables to determine the status of each input. missingName and missingMessage are easy. Return true if value is empty:
  missingName: function () { return this.name === ''; },
  missingMessage: function () { return this.message === ''; },
wrongNumber is a little more complex, but not bad at all. Return true if the value is not a number or it’s less than 1 or it’s greater than 10. missingEmail return true if the value has not a valid format or null.
 wrongNumber: function () {
  return (
    this.isNumeric(this.number) === false ||
    this.number < 1 ||
    this.number > 10
  )
},

missingEmail: function () {
   return (
     this.isEmail(this.email) === null)
},
Oops, we’re calling isNumeric() and isEmail() but we haven’t coded it, yet. Here’s what it looks like:
isNumeric: function (n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
},
isEmail: ( str ) => {      
   let regexp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/     
   return str.match(regexp);
}
We're actually done with the JavaScript except for the actual validateForm() and onSubmit function. For that one, we just want to tell our app the user attempted to submit the form and prevent it from submitting if missingName, missingEmail, missingMessage or wrongNumber are true. If all the values are validated, we call onSubmit method.
validateForm: function (event) {
   this.attemptSubmit = true;
   if (this.missingName || this.wrongNumber || this.missingMessage || this.missingEmail) {
       event.preventDefault();
   } else {
       this.onSubmit();
   }       
Done with JavaScript. Back in the HTML, we need to fire the validateForm() function when the form is submitted.

  <form id="form" method="post" v-on:submit.prevent="validateForm">


Then, add the (Bootstrap) has-warning class for each input. We only want to add this class if BOTH:
1. The user has attempted to submit the form, and 2. The value is not valid
<div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && missingName }">
...
<div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && wrongNumber }">
...
<div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && missingEmail }">
...
<div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && missingMessage }">

Finally, we only want the feedback elements to appear under those same circumstances:
 <span id="helpBlock" class="help-block" v-if="attemptSubmit && missingName">This field is required.</span>
.....
 <span id="helpBlock" class="help-block" v-if="attemptSubmit && wrongNumber">Make sure this is a number between 1 and 10.</span>
......
 <span id="helpBlock" class="help-block" v-if="attemptSubmit && missingEmail">Email is invalid.</span>
......
 <span id="helpBlock" class="help-block" v-if="attemptSubmit && missingMessage">This field is required.</span>
That’s it! On load, the form looks like…
If you try to submit with an empty fields, a warning appears.
The nice part is that, the way we’ve coded it, when the user corrects their mistake, the warning goes away immediately.

Form Submission
After the validation is successful, we will submit using PHP. In order to submit the POST values we are going to use. Axios. Axios is a promise-based HTTP client that works both in the browser and in a node.js environment. It basically provides a single API for dealing with XMLHttpRequests and node’s http interface.

Before using axios, you first need to install it. Adding Axios to your project is easy. There are two options:
1. Install Axios with Node Package Manager as follows:
  $ npm install axios
2. The easiest way is to include Axios by using a Content Delivery Network, e.g. by including the following <script> tag in your index.html file:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Simply import axios or require it as you do with any other dependency in node as below (if you are using nodeJs and webpack only):

import axios from 'axios';

or

var axios = require('axios');

A frequently overlooked but very useful capability Axios provides is the ability to create a base instance that allows you to share a common base URL and configuration across all calls to the instance.

onSubmit () {
    
     if (process.env.NODE_ENV === 'development') {
            axios.defaults.baseURL = 'http://localhost:8888/your-project-name/php'
      }

      axios.post('post.php', {
                'name': this.name,
                'email': this.email,
                'message': this.message,
                'number': this.number               
        }).then(response => {
            if (response.data.error) {
                    console.log('error', response.data.error)
           } else {
                this.postStatus = true
                console.log('success', response.data.message)                   
           }
        }).catch(error => {
              console.log(error.response)
     }); 
}

Create a folder 'php' and create a file 'post.php' under it.
/* php/post.php */

<?php
header('Content-type: application/json');
header('Access-Control-Allow-Headers: Content-Type');
header("Access-Control-Allow-Origin: *");

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

$name = $input['name'];
$email = $input['email'];
$message = $input['message'];
$number = $input['number'];


$result['message'] = '';
$result['error']  = false;

if($name){
  $result['message']  = "Posted Values => ".$name."-".$email."-".$message."-".$number;
  $result['error']  = false;
}
else {
  $result['error']  = 'Form submission failed.';
}


echo json_encode($result);

file_get_contents(php://input) - gets the raw POST data and this is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request. The PHP superglobal $_POST, only is supposed to wrap data that is either
1. application/x-www-form-urlencoded (standard content type for simple form-posts) or
2. multipart/form-data-encoded (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't). But if you are working with Ajax a lot, this probably also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. The content would now be 'application/json' (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet). The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).

After the form is submitted, you will see confirmation message as below.
I have created a component called 'Form.Vue' with above pieces. Here is the complete source code.

//Form.Vue

<template>  
    <div id="app" class="container">
      <div class="row justify-content-center">
        <div class="col-md-6" v-if="!postStatus">
          <form id="form" method="post" v-on:submit.prevent="validateForm">
            <div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && missingName }">
              <label class="control-label" for="name">Name</label>
              <input id="name" name="name" class="form-control" type="text" v-model="name">
              <span id="helpBlock" class="help-block" v-if="attemptSubmit && missingName">This field is required.</span>
            </div>
            
            <div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && wrongNumber }">
              <label class="control-label" for="number">Enter a number between 1 and 10</label>
              <input id="number" name="number" class="form-control" type="text" v-model="number">
              <span id="helpBlock" class="help-block" v-if="attemptSubmit && wrongNumber">Make sure this is a number between 1 and 10.</span>
            </div>

             <div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && missingEmail }">
              <label class="control-label" for="name">Email</label>
              <input id="email" name="email" class="form-control" type="text" v-model="email">
              <span id="helpBlock" class="help-block" v-if="attemptSubmit && missingEmail">Email is invalid.</span>
            </div>

             <div class="form-group" v-bind:class="{ 'has-warning': attemptSubmit && missingMessage }">
              <label class="control-label" for="message">Enter a Message</label>
              <textarea  name="message" class="form-control" type="text" v-model="message"></textarea>
              <span id="helpBlock" class="help-block" v-if="attemptSubmit && missingMessage">This field is required.</span>
            </div>                 
            
            <button class="btn btn-primary">Submit</button>
          </form>
        </div><!-- /col -->

         <div class="col-md-8" v-if="postStatus">

           <h1>The form is submitted successfully.</h1>

         </div> 
      </div><!-- /row -->

    </div><!-- /container -->
</template>

<script>

import axios from 'axios'
  
  export default {   
    data () {
      return {
        name: '',
        email: '',
        message: '',
        number: '',
        attemptSubmit: false,
        postStatus: false
      }
    },
    computed: {
        missingName: function () { return this.name === '' },
        missingMessage: function () { return this.message === '' },
        missingEmail: function () {
          return (
            this.isEmail(this.email) === null)
        },
        wrongNumber: function () {
          return (
            this.isNumeric(this.number) === false ||
            this.number < 1 ||
            this.number > 10
          )
      },
  },
  methods: {
     isNumeric: function (n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    },
    isEmail: ( str ) => {      
      let regexp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/     
      return str.match(regexp);
    },       
    validateForm: function (event) {
      this.attemptSubmit = true;
      if (this.missingName || this.wrongNumber || this.missingMessage || this.missingEmail) {
          event.preventDefault();
      } else {
         this.onSubmit();
      }       
    },
    onSubmit () {
    
       if (process.env.NODE_ENV === 'development') {
                axios.defaults.baseURL = 'http://localhost:8888/your-project-name/php'
        }

       axios.post('post.php', {
                'name': this.name,
                'email': this.email,
                'message': this.message,
                'number': this.number               
            }).then(response => {
                if (response.data.error) {
                    console.log('error', response.data.error)
                } else {
                    this.postStatus = true
                    console.log('success', response.data.message)                   
                }
            }).catch(error => {
                console.log(error.response)
            }); 
      }
  }   
}
</script>

Source: Form Validation with Vue.js

Wednesday, August 16, 2017

How to Dockerize a Node.js app?

The goal of this example is to show you how to get a Node.js application into a Docker container. In this article we'll show you how to create a Docker image for an application written in Node.js.

Why should I dockerize my application
You might've heard about the whole Docker thing, but that still doesn't answer the question: "why bother?" Well, that's why:

1. You can launch a fully capable development environment on any computer supporting Docker; you don't have to install libraries, dependencies, download packages, mess with config files etc.
2. The working environment of the application remains consistent across the whole workflow. This means the app runs exactly the same for developer, tester, and client, be it on development, staging or production server.

In short, Docker is the counter-measure for the age-old response in the software development: "Strange, it works for me!"

Part 1: Create the Node.js app
In the first part of this guide we will create a simple web application in Node.js, then we will build a Docker image for that application, and lastly we will run the image as a container.

Install Node.js
If you've never worked with Node.js before, kick off with installing the npm manager: nodejs.org/en/download/package-manager

Install NPM and Express Framework
First, create a new directory 'helloworld' where all the files would live and initialize npm.
 $ mkdir helloworld 
 $ cd helloworld
 $ npm init
When asked for the details of the application (name, version, etc.), just confirm the default values with enter.

Npm will create a package.json that will hold the dependencies of the app. Let's add the Express Framework as the first dependency:
 $ npm install express --save
The file should look like this now:
{
  "name": "helloworld",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.15.2"
  }
}
With everything installed, we can create a server.js file that defines a web app using the Express.js framework with a simple HTTP server that will serve our Hello World website:
//Load express module with `require` directive
var express = require('express')
var app = express()

//Define request response in root URL (/)
app.get('/', function (req, res) {
  res.send('Hello World!')
})

//Launch listening server on port 8081
app.listen(8081, function () {
  console.log('app listening on port 8081!')
})
Run the app
The application is ready to launch:
  $ node server.js
Go to http://localhost:8081/ in your browser to view it.

Part 2: Dockerizing Node.js application
Every application requires a specific working environment: pre-installed applications, dependencies, data bases, everything in specific version. Docker containers allow you to create such environments. Contrary to VM, however, the container doesn't hold the whole operating system—just applications, dependencies, and configuration. This makes Docker containers much lighter and faster than regular VM's.

In this part of the article, we'll look at how you can run this app inside a Docker container using the official Docker image.

Install Docker
Docker allows you to package an application with all of its dependencies into a standardized unit, called a container, for software development. A container is a stripped-to-basics version of a Linux operating system. An image is software you load into a container.

Begin with installing Docker for your type of OS: Docker installation

Write Dockerfile
The Docker image is created with instructions written in the Dockerfile. Let's add Dockerfile to the directory with our application. Create an empty file called Dockerfile:
 touch Dockerfile
Open the Dockerfile in your favorite text editor. The first thing we need to do is define from what image we want to build from.
Line 1: Use another Docker image for the template of my image. We shall use the official Node.js image with Node v8.
 FROM node:8.3.0
Line 2: Set working dir in the container to /app. We shall use this directory to store files, run npm, and launch our application:
 # Create app directory
 WORKDIR /app
Line 3-5: Copy application to /app directory and install dependencies. If you add the package.json first and run npm install later, Docker won't have to install the dependencies again if you change the package.json file. Please note that if you are using npm version 5 or later you will also want to copy package-lock.json, which is generated once you run npm install. This results from the way the Docker image is being built (layers and cache), and this is what we should do:
 # Install app dependencies
 COPY package.json /app

 # For npm@5 or later, copy package-lock.json as well
 # COPY package.json package-lock.json /app

 RUN npm install
Note that, rather than copying the entire working directory, we are only copying the package.json file. This allows us to take advantage of cached Docker layers.
To bundle your app's source code inside the Docker image, use the COPY instruction:
 # Bundle app source
 COPY . /app
Your app binds to port 8081 so you'll use the EXPOSE instruction to have it mapped by the docker daemon:
 EXPOSE 8081
Last but not least, define the command to run your app using CMD which defines your runtime. This line describes what should be executed when the Docker image is launching. What we want to do is to run our application:
 CMD node server.js
Summing up, the whole Dockerfile should look like this:
 FROM node:8.3.0

 # Create app directory
 WORKDIR /app

 # Install app dependencies
 COPY package.json /app

 # For npm@5 or later, copy package-lock.json as well
 # COPY package.json package-lock.json /app

 RUN npm install

 # Bundle app source
 COPY . /app

 EXPOSE 8081
 CMD node server.js

.dockerignore file
Create a .dockerignore file in the same directory as your Dockerfile with following content:
 node_modules
 npm-debug.log
This will prevent your local modules and debug logs from being copied onto your Docker image and possibly overwriting modules installed within your image.

Build Docker image
Go to the directory that has your Dockerfile and run the following command to build the Docker image. The -t flag lets you tag your image so it's easier to find later using the docker images command:
 $ docker build -t hello-world .
Run the image
The application has been baked into the image. Dinner time! Execute the following string to launch the container and publish it on the host with the same port 8081:
 $ docker run -p 8081:8081 hello-world
Running your image with -p flag redirects a public port to a private port inside the container.

Print the output of your app
# Get container ID
$ docker ps

# Print app output
$ docker logs 

# Example
  app listening on port 8081!

We hope this tutorial helped you get up and running a simple Node.js application on Docker.

Sources:
Dockerizing a Node.js web app
How to Dockerize a Node.js application

Thursday, July 6, 2017

How To Use jQuery Into Vue.js Using Webpack?

For global access to jQuery there exists several methods. In my most recent vue.js and webpack project, I wanted global access to jQuery so I added using the following method.

Suppose you have Vue.js project created with vue-cli and node. (e.g. vue init webpack my-project ).
Go to project dir and run
  npm install jquery --save-dev
Open file build/webpack.base.conf.js and add plugins :
var webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
      jQuery: 'jquery'
    })
  ],
  ....
Go to project dir and run
   npm run dev
This then means that jquery is accessible from within the JavaScript source code via global references $, jquery and jQuery. Now you are ready to go.

Friday, June 16, 2017

How To Calculate The Percentage Of A Number Using PHP?

This is a short guide on how to calculate the percentage of a given number in PHP. For example: What is 25% of 100? Or what is 10% of 728?

In this code snippet, I have put each calculation on its own separate line, just to make the math a little clearer:
<?php
 
//My number is 928.
$myNumber = 928;
 
//I want to get 25% of 928.
$percentToGet = 25;
 
//Convert our percentage value into a decimal.
$percentInDecimal = $percentToGet / 100;
 
//Get the result.
$percent = $percentInDecimal * $myNumber;
 
//Print it out - Result is 232.
echo $percent;
A quick summary of what we did:
1. We used the number 928 for example purposes.
2. We specified that we wanted to get 25% of 928.
3. We converted our percentage value into a decimal number by dividing it by 100. This turns 25 into 0.25.
4. We then multiplied 0.25 by 928.
5. The end result is 232, which means that 25% of 928 is 232.

Function
If you're looking for a simple PHP function to use in your projects, then you can use the following:
/**
 * A simple PHP function that calculates the percentage of a given number.
 * 
 * @param int $number The number you want a percentage of.
 * @param int $percent The percentage that you want to calculate.
 * @return int The final result.
 */
function getPercentOfNumber($number, $percent){
    return ($percent / 100) * $number;
}

echo getPercentOfNumber(928, 25); 

//output 232

Source: PHP: Calculate The Percentage Of A Number.

Monday, May 29, 2017

How To Access Pages Without the PHP Extension Using .htaccess?

There are a number of ways to make "clean URLs" work on your site, but this one is pretty straight forward. It allows you to access /any-page.php by simply going to /any-page. Just place the following into your .htaccess file (and make sure that mod_rewrite is enabled):
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

The nice thing about this is that it doesn't affect querystrings. With this solution, both of these URLs are effectively the same:
http://example.com/page.php?id=123
http://example.com/page?id=123

Source: Access Pages Without the PHP Extension Using .htaccess

Monday, May 8, 2017

Integrating ReactJS, Typescript, and Webpack Part 2

For those of you who want to dive in and see the final version of the code, check it out here!

ReactJS is a library released by Facebook and unlike other JavaScript frameworks out there (i.e. Angular, Backbone, Ember, etc), it’s goal is to simply represent the 'View' layer in the traditional Model View Controller (MVC) paradigm.

ReactJS, Typescript, and Webpack
Now that we have a Typescript and Webpack integrated on previous chapter Part 1, let's go ahead and throw ReactJS into the mix as well. Let's first NPM install ReactJS as a dependency.
  npm install --save react react-dom
Since we're using a 3rd party library with Typescript, we're going to need to NPM install Typings as well. You might be asking, "what is Typings?". Typings is simply the tool we use to manage all of the Typescript definition files. It’ll allow us to easily download and use all of our 3rd party Typescript definition files.
 npm install --save-dev typings
Here’s how our package.json file looks now:
{
  "name": "typescript-webpack-react",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.3.2",
    "typings": "^2.1.1",
    "webpack": "^2.1.0-beta.22"
  },
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  }
}
Let's download the Definitely Typed files for React and ReactDOM. We'll use Typings to do the installation:
 node_modules/.bin/typings install --save react react-dom

Note: The preferred method for installing typings for Typescript >2.0 is now
npm install --save-dev @types/react @types/react-dom

A couple of things to notice:
1. Because we didn't install Typings globally, we had to prefix the command with where the Typings module is located: node_modules/.bin/typings.
2. The "--save" flag indicates that we want to save the React and ReactDOM definition files.
3. Notice that our directory now has a typings directory as well as a "typings.json" file. The typings.json file specifies all of the definition files we have installed, and the typings directory contains the actual definition files.

Now that we're trying to use React with Typescript, we should update a Typescript configuration file tsconfig.json which we have set up on Part 1.
{
    "compilerOptions": {
        "jsx": "react",
        "module": "commonjs",
        "noImplicitAny": true,
        "outDir": "./build/",
        "preserveConstEnums": true,
        "removeComments": true,
        "target": "ES5"
    },
        "exclude": [
         "node_modules"        
    ]
}

A couple of things to note here:
1. Make sure that tsconfig.json is located in the root directory.
2. If you want to learn more about the tsconfig.json file, check this out. Of particular importance to us is the "jsx" key which tells Typescript to accept React’s JSX syntax whenever we create a file with a ".tsx" extension.
3. Notice that we’re specifying files and directories to include from going through the Typescript compiler.

Since we're using React now, let’s rename our src/some_module.ts file to src/Hello.tsx, and create a simple Hello component:
// Remember to rename your file to Hello.tsx and
// place it within your src/ directory

import * as React from "react";

interface HelloProps {
  name: string;
}

class Hello extends React.Component<HelloProps, {}> {
  render() {
    return <div>Hello, {this.props.name}</div>;
  }
}

export default Hello;
Let’s also rename our src/app.ts file to src/app.tsx, and change the content to the following:

// Remember to rename the file from app.ts to app.tsx
// and to keep it in the src/ directory.

import * as React from "react";
import * as ReactDOM from "react-dom";
import Hello from "./Hello";

ReactDOM.render(
  <Hello name="Willson" />,
  document.getElementById("root")
);
Since we’re injecting our rendered Hello component into the DOM, we’ll need to modify our index.html file as well.
<--index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Getting Started with Typescript, Webpack, and ReactJS </title>
  </head>
  <body>
<!-- this is where our Hello component will get rendered into -->
    <div id="root"></div>

    <script src="build/bundle.js"></script>
 </body>
</html>
We’ve renamed our application's entry point, which means we'll need to modify our webpack.config.js file as well. It's a minor change — we just need to change it to the correct file extension.
var path = require("path");

var config = {
  /*
   * app.tsx represents the entry point to your web application. Webpack will
   * recursively go through every "require" statement in app.ts and
   * efficiently build out the application's dependency tree.
   */
  entry: ["./src/app.tsx"],

  /*
   * The combination of path and filename tells Webpack what name to give to
   * the final bundled JavaScript file and where to store this file.
   */
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "bundle.js"
  },

  /*
   * resolve lets Webpack now in advance what file extensions you plan on
   * "require"ing into the web application, and allows you to drop them
   * in your code.
   */
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },

  module: {
    /*
     * Each loader needs an associated Regex test that goes through each
     * of the files you've included (or in this case, all files but the
     * ones in the excluded directories) and finds all files that pass
     * the test. Then it will apply the loader to that file. I haven't
     * installed ts-loader yet, but will do that shortly.
     */
    loaders: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        exclude: /node_modules/
      }
    ]
  }
};

module.exports = config;
And if you run "npm run build" in your terminal again, you should see Webpack do its thing and generate a new bundle.js file. If we open our index.html in the browser, you'll see the fruits of your labor!

Conclusion
Hopefully you've found this tutorial helpful for getting you started using these 3 technologies together. There’s tons more you can do (i.e. use webpack-dev-server, set up source maps in Typescript, etc) but I’ll leave it for you to continue exploring!

Source: Getting Started with ReactJS, Typescript, and Webpack

Friday, May 5, 2017

Getting Started with Typescript and Webpack Part 1

In this tutorial, I want to briefly describe Typescript and Webpack technologies and how to get started using both of them together. So let's get started!

Typescript is developed and maintained by Microsoft and it’s best described as JavaScript with an optional Type system. It’s a complete superset of JavaScript, which means that every bit of JavaScript code you’ve written is already valid Typescript code.

Webpack is a module bundler, and this simply means that it can take many different JavaScript files / modules and efficiently combine them together into one final JavaScript file.

For those of you who want to dive in and see the final version of the code, check it out here!

Typescript and Webpack

Let's go ahead and open a terminal window, create a new project directory, and cd into it.
Next, let's create the following directory structure inside of the project.
At the root of your project directory, run "npm init -y" which is a NPM command that creates a boilerplate package.json file for you.
Next, we'll install Typescript and Webpack. Notice that I installed Typescript and Webpack beta version with the " — save-dev" flag, which simply means that I want to save these packages as developer dependencies (i.e. these are packages that the actual web application doesn’t need but are used by developers to produce the final web application).
   npm install --save-dev typescript webpack@2.1.0-beta.22
Here’s how my package.json file and root directory look right now.
  {
   "name": "typescript-webpack",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^2.3.2",
    "webpack": "^2.1.0-beta.22"
  }
}
In order to set up Webpack, I'll add a webpack.config.js file in the root directory and it’ll have the following content:
var path = require("path");

var config = {
  /*
   * app.ts represents the entry point to your web application. Webpack will
   * recursively go through every "require" statement in app.ts and
   * efficiently build out the application's dependency tree.
   */
  entry: ["./src/app.ts"],

  /*
   * The combination of path and filename tells Webpack what name to give to
   * the final bundled JavaScript file and where to store this file.
   */
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "bundle.js"
  },

  /*
   * resolve lets Webpack now in advance what file extensions you plan on
   * "require"ing into the web application, and allows you to drop them
   * in your code.
   */
  resolve: {
    extensions: ["", ".ts", ".tsx", ".js"]
  },

  module: {
    /*
     * Each loader needs an associated Regex test that goes through each
     * of the files you've included (or in this case, all files but the
     * ones in the excluded directories) and finds all files that pass
     * the test. Then it will apply the loader to that file. I haven't
     * installed ts-loader yet, but will do that shortly.
     */
    loaders: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        exclude: /node_modules/
      }
    ]
  }
};

module.exports = config;

Next, let's install ts-loader by executing npm install ts-loader (remember to save it as a developer dependency).
 npm install ts-loader --save-dev
We’re almost there — now we just need to create a couple of files: index.html, src/app.ts, and src/some_module.ts
<--index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Getting Started with Typescript, Webpack</title>
  </head>
  <body>
    <script src="build/bundle.js"></script>
 </body>
</html>
// app.ts

import greeting from "./some_module";

console.log(greeting);
// some_module.ts
const greeting: string = "Hello World!";

export default greeting;
Now that we’re trying to use Typescript, we should create a Typescript configuration file in the root directory — be sure to name it tsconfig.json.
{
    "compilerOptions": {       
        "module": "commonjs",
        "noImplicitAny": true,
        "outDir": "./build/",
        "preserveConstEnums": true,
        "removeComments": true,
        "target": "ES5"
    },
        "exclude": [
         "node_modules"     
    ]
}
We'll also want to modify our package.json to include a NPM script which runs Webpack for us. Added a "build" script to the package.json file. Here's how my package.json file and project directory look right now.
{
  "name": "typescript-webpack",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.3.2",
    "webpack": "^2.1.0-beta.22"
  }
}
We're finally here — the moment of truth! If we run "npm run build" in our root directory, we should see Webpack do its magic and produce a bundle.js file in the build directory. If we open the index.html file and look at the console, we should see our greeting "Hello World!" as below.


In next tutorial, We integrate ReactJS to the typescript and webpack. Click Integrating ReactJS, Typescript, and Webpack Part 2. to continue reading.

For those of you who want to dive in and see the final version of the code, check it out here!

Source: Getting Started with ReactJS, Typescript, and Webpack

Tuesday, February 28, 2017

How To Detect HTTP Or HTTPS in JavaScript?

You can use location.protocol to detect the protocol that the site is using. Lets say we have the url https://www.example.com. We can use following code to detect if it has HTTP or HTTPS.
console.log(location.protocol);
//output => https:

You can change the protocol of the site simply by using following logic:
var protocol = location.protocol === 'https:' ? 'http' : 'https';

console.log(protocol);
//output => http

How to solve nodejs Error: listen EADDRINUSE?

In this post we are going to discuss about how to solve Node.js error: listen EADDRINUSE. EADDRINUSE actually means that the port number which you are binding to the server using listen() is already in use.

Error: listen EADDRINUSE means the port which you want to assign/bind to your application server is already in use. You can either assign another port to your application.

Or if you want to assign the same port to the app. Then kill the application that is running at your desired port.

If any application is already running on 3000 then you will get the below error (Error: listen EADDRINUSE). Here is the screenshot of error:

To solve this error either you start your node server on another port or close the program using that port. If you use lsof, you can see what process is bound to the port with lsof -i:3000, and then force kill it by grabbing the process id (aka pid) and kill it with a kill -9 $pid.

You'll only see it if you have permissions; if you're running lsof as a different user than the app, try prefixing lsof -i:$port with sudo to make sure you have adequate permissions.

What really helped for me was:
killall -9 node
But this will kill a system process.

Ref: https://teamtreehouse.com/community/hi-its-throwing-an-error-listen-eaddrinuse-3000-unhandled-error-event

Monday, February 13, 2017

What New ES6/7 Has To Offer?

This post will give you a quick introduction to ES6 (aka ECMAScript 2015). If you don't know what is ES6, it’s a new JavaScript implementation. If you haven't taken a look at ES6/7 yet you're missing out on some amazing advances to the JavaScript language.

Some of the important features of ES6/7 are below:
• let, const
• Template Strings/literals
• Arrow Functions
• Classes
• Destructuring
• Modules
• Native Promises
• Async Await
• Spread Operators
• Rest Parameters

Let + Const
In ES5, you declare variables via var. Such variables are function-scoped, their scopes are the innermost enclosing functions. In ES6, you can additionally declare variables via let and const. Such variables are block-scoped, their scopes are the innermost enclosing blocks.

let is the new var and block-scoped: they only exist in the block they are defined in.
var num = 0; //globally scoped

for (let i = 0; i < 10; i++) { //i is block scoped
  num += i;
  console.log('value of i in block: ' + i);
}

console.log('Is i defined here?: ' + (typeof i !== 'undefined')); //Is i defined here?: false 

Constants (also known as "immutable variables"), i.e., variables which cannot be re-assigned new content. const is single-assignment. const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards.
const foo;
    // SyntaxError: missing = in const declaration

const bar = 123;
bar = 456;
    // TypeError: `bar` is read-only

Template Strings/literals
Template literals are a new feature in ES6 to make working with strings and string templates easier. Template strings provide syntactic sugar for constructing strings. You wrap your text in `backticks` and you'll get the features described below.
• They can be multi-line. Finally!
• You can interpolate variables in them
• You can actually interpolate using any kind of expression, not just variables
• You can construct raw templates that don't interpret backslashes
// Basic literal string creation
`This is a pretty little template string.`

// Multiline strings
`In ES5 this is
 not legal.`

// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Unescaped template strings
String.raw`In ES5 "\n" is a line-feed.`

var today = new Date()
var text = `the time and date is ${today.toLocaleString()}`
console.log(text)
// <- 'the time and date is 8/26/2015, 3:15:20 PM'



Arrow functions
Fat arrow functions, also known as just arrow functions are a brand new feature in ECMAScript 2015 (formerly ES6). Arrows are a function shorthand using the => syntax. Arrow functions serve two main purposes: more concise syntax and sharing lexical this with the parent scope. Arrow functions behave differently than traditional JavaScript functions in a number of important ways:
• Lexical this binding – The value of this inside of the function is determined by where the arrow function is defined not where it is used.
• Not newable – Arrow functions cannot be used a constructors and will throw an error when used with new.
• Can’t change this – The value of this inside of the function can’t be changed, it remains the same value throughout the entire lifecycle of the function.
var reflect = value => value;

// effectively equivalent to:

var reflect = function(value) {
    return value;
};
When there is only one argument for an arrow function, that one argument can be used directly without any further syntax. The arrow comes next and the expression to the right of the arrow is evaluated and returned. Even though there is no explicit return statement, this arrow function will return the first argument that is passed in.

If you are passing in more than one argument, then you must include parentheses around those arguments. For example:

var sum = (num1, num2) => num1 + num2;

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
};

The sum() function simply adds two arguments together and returns the result. The only difference is that the arguments are enclosed in parentheses with a comma separating them (same as traditional functions).

When you want to provide a more traditional function body, perhaps consisting of more than one expression, then you need to wrap the function body in braces and explicitly define a return value, such as:
var sum = (num1, num2) => { return num1 + num2; }

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
};
You can more or less treat the inside of the curly braces as the same as in a traditional function with the exception that arguments is not available.

Because curly braces are used to denote the function’s body, an arrow function that wants to return an object literal outside of a function body must wrap the literal in parentheses. For example:
var getTempItem = id => ({ id: id, name: "Temp" });

// effectively equivalent to:

var getTempItem = function(id) {

    return {
        id: id,
        name: "Temp"
    };
};
The concise syntax for arrow functions also makes them ideal as arguments to other functions. For example, if you want to sort an array using a custom comparator in ES5, you typically write something like this:
var result = values.sort(function(a, b) {
    return a - b;
});
That’s a lot of syntax for a very simple procedure. Compare that to the more terse arrow function version:
var result = values.sort((a, b) => a - b);
The array methods that accept callback functions such as sort(), map(), and reduce() all can benefit from simpler syntax with arrow functions to change what would appear to be more complex processes into simpler code.

Classes
ES6 Classes formalize the common JavaScript pattern of simulating class-like inheritance hierarchies using functions and prototypes. They are effectively simple sugaring over prototype-based OO, offering a convenient declarative form for class patterns which encourage interoperability. Classes support prototype-based inheritance, constructors, super calls, instance and static methods.
class someClass {
    constructor(name, age) {
        this.name = name;
        this.age = age;
 }

    sayName() {
        alert(this.name);
    }

    sayAge() {
        alert(this.age);
    }
}

var myInstance = new someClass('dwayne', 27);
myInstance.sayName();
Class inheritance
class Child extends someClass {
    constructor(name, age) {
        super(name, age);
    }
    
    // Override the someClass method above
    sayName() {
        // This will call someClass.sayName() triggering the old alert
        // Which will just display our name
        super.sayName();
        
        // This will trigger the new alert which has labels and our age
        alert('Name:' + this.name + ' Age:' + this.age);
    }
}

var myChild = new Child('dwayne', 27);
myChild.sayName();
As you can see, classes are extremely flexible especially when extending a base class and having the ability to easily override a parent method without needing to write any boilerplate logic to do so.
In the ES6 classes syntax we have access to a function called super() which essentially just calls the parent function depending on the context and then returns the result. Calling super.parentMethodName() from within a child class will call the base class you inherited.

Destructuring
Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

/*Destructuring objects*/
const obj = { first: 'Jane', last: 'Doe' };
const {first: f, last: l} = obj;
    // f = 'Jane'; l = 'Doe'

// {prop} is short for {prop: prop}
const {first, last} = obj;
    // first = 'Jane'; last = 'Doe'


/*Array destructuring*/
const iterable = ['a', 'b'];
const [x, y] = iterable;
    // x = 'a'; y = 'b'


// list matching
var [a, ,b] = [1,2,3];
a === 1;
b === 3;

Modules
ES6 is the first time that JavaScript has built-in modules. In ES6 each module is defined in its own file. The functions or variables defined in a module are not visible outside unless you explicitly export them. This means that you can write code in your module and only export those values which should be accessed by other parts of your app.

ES6 modules are declarative in nature. To export certain variables from a module you just use the keyword export. Similarly, to consume the exported variables in a different module you use import.

Let's create a simple module that has two utility functions:
1. generateRandom() : Generates a random number.
2. sum() : Adds two numbers.

Next, let's create a file named utility.js for the module:
//utility.js

 function generateRandom() {
    return Math.random();
 }

 function sum(a, b) {
    return a + b;
 }

 export { generateRandom, sum }
That's it! The export keyword on the last line exports the two functions. As you can see, the exported functions are listed in curly braces separated by a comma. You can also rename the values while exporting like this:
 export {generateRandom as random, sum as doSum}

Now, let’s see how to consume the exported values in a different module.
//app.js

 import { generateRandom, sum } from 'utility';

 console.log(generateRandom()); //logs a random number
 console.log(sum(1, 2)); //3
Note the first line. This imports the exported values from the module utility. If you want to import a single value (for example sum), you can do it by writing the following:
import { sum } from 'utility';

You can also import the entire module as an object and access exported values as properties. So, we can modify our code as following:
 import 'utility' as utils;

 console.log(utils.generateRandom()); //logs a random number
 console.log(utils.sum(1, 2)); //3
Rest of the topics are coming soon.

References: Understanding ECMAScript 6 arrow functions
Learn ES2015
http://exploringjs.com/es6/index.html
ES6 Template Literals in Depth
Understanding ES6 Modules

Tuesday, February 7, 2017

Automate Your Tasks Easily with Gulp.js Part 2

Determining Folder Structure
Gulp is flexible enough to work with any folder structure. You'll just have to understand the inner workings before tweaking it for your project.


source is the folder where we will do our work.
assets/stylesheets/style.css will be created by gulp when we process and combine our SASS files in source/scss.
The assets/javascript/bundle.js file will be created by gulp when we minify and combine all our JS files.

Writing Your First Gulp Task
Before we get right into the code I think it's very important to mention that gulp only has 4 top level functions.
gulp.task defines your tasks. Its arguments are name, deps and fn.

gulp.task('task-name', function() {
  // Stuff here
});

gulp.task('dependentTask', ['task-name'], function() {
  //do stuff after 'task-name' is done.
});
'task-name' refers to the name of the task, which would be used whenever you want to run a task in Gulp. You can also run the same task in the command line by writing gulp task-name.

gulp.src points to the files we want to use. It's parameters are globs and an optional options object. It uses .pipe for chaining it's output into other plugins.

gulp.dest points to the output folder we want to write files to.

gulp.src and gulp.dest used to simply copy files looks like:
gulp.task('copyHtml', function() {
  // copy any html files in source/ to public/
  gulp.src('source/*.html').pipe(gulp.dest('public'));
});

gulp.watch method that checks to see if a file was saved. gulp.watch like gulp.task has two main forms. Both of which return an EventEmitter that emits change events. The first of which takes a glob, an optional options object, and an array of tasks as it's parameters.
// Gulp watch syntax
gulp.watch('files-to-watch', ['tasks', 'to', 'run']); 
If we want to watch all javascript files and run the jshint task whenever a javascript file is saved, we just have to replace files-to-watch with the source/javascript/**/*.js, and ['tasks', 'to', 'run'] with ['jshint'].
gulp.watch('source/javascript/**/*.js', ['jshint']);
In the above code block, when any files in the source/javascript subfolders that have an extension of .js change, then the task jshint will be run against those files.

Once gulp is installed we have to give it some instruction so it knows what tasks for perform for us. But, first, we need to figure out exactly what tasks we need to run in our project.
Lint our JavaScript(check for errors) using jshint. We’ll also need a reporter for jshint to make the output nicely formatted and color coded.
Compile our Sass files.

Install Required Plugins
$ npm install --save-dev gulp-jshint jshint-stylish gulp-sass
This will install all of the plugins we will need and add them to our devDependencies in our package.json file like we did when we installed gulp.

Now we’ll add the lint task to our gulpfile.
/* File: gulpfile.js */

// grab our packages
var gulp   = require('gulp');
var jshint = require('gulp-jshint');

// define the default task and add the watch task to it
gulp.task('default', ['watch']);

// configure the jshint task
gulp.task('jshint', function() {
  return gulp.src('source/javascript/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
  gulp.watch('source/javascript/**/*.js', ['jshint']);
});
So lets step through what we’ve done.
We’ve rewritten our default task to have the watch task as dependency. What this means is that running
$ gulp
will run the watch task.

Now lets look at the new jshint task. It sources any .js files that exist in source/javascript or any of it’s subdirectories. So a file at source/javascript/courage.js would be picked up for the task just as well. These files are then passed into our gulp-jshint plugin, which then passes it into the stylish reporter to give us the jshint results.

We can run this task by doing:
$ gulp jshint

Alright, now what about that watch task. It's simple actually, if a change is detected in any of our javascript files, it runs the jshint task.

Now we’ll add the compile SASS task to our gulpfile.
Sass serves as a way to extend CSS giving support for variables, nested rules, mixins, inline imports, and more. For sass compilation we’ll use gulp-sass.
/* file: gulpfile.js */

var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var sass   = require('gulp-sass');


/* jshint task would be here from above */

gulp.task('build-css', function() {
  return gulp.src('source/scss/**/*.scss')
    .pipe(sass())
    .pipe(gulp.dest('public/assets/stylesheets'));
});

// define the default task and add the watch task to it
gulp.task('default', ['watch']);


/* updated watch task to include sass */

gulp.task('watch', function() {
  gulp.watch('source/javascript/**/*.js', ['jshint']);
  gulp.watch('source/scss/**/*.scss', ['build-css']);
});
We can run this task by doing:
$ gulp build-css


Summary
We’ve only scratched the surface of gulp. Gulp can be as complex or as simple as you need it to be, and because it’s just code you can do just about anything you want as a task.

Sources and Ref:
https://scotch.io/tutorials/automate-your-tasks-easily-with-gulp-js
https://travismaynard.com/writing/getting-started-with-gulp

Wednesday, January 18, 2017

Automate And Enhance Your Workflow With Gulp Part 1

Gulp is a streaming build system, by using node's streams file manipulation is all done in memory, and a file isn’t written until you tell it to do so. In short, Gulp is a task runner which uses Node.js.

Much like Grunt, Gulp is a javascript task runner. Gulp however prefers code over configuration. Being that your tasks are written in code, gulp feels more like a build framework, giving you the tools to create tasks that fit your specific needs.

Enough theory — let's start using Gulp.

Step 1: Installing Node.js
You need to have Node.js (Node) installed onto your computer before you can install Gulp. Node.js can be downloaded for Windows, Mac and Linux at nodejs.org/download/. Once your download completes, run that application and you should be all ready to go.

Once installed, open a command prompt and enter:
node -v
Again, this should return the version number on the next line. Now, let's do the same for npm.
npm -v
Again, this should return the version number on the next line. If you didn't get a response, then it may mean that Node didn’t install correctly or you may need to restart your command line application.

Step 2: Installing Gulp
Now, let's meet npm and install Gulp. npm is a package manager for Node that will enable you to install additional modules for use in your projects from the command line.

We can now install Gulp using npm, jump back to your command-line application and type:
$ npm install -g gulp
The npm install command we've used here is a command that uses Node Package Manager (npm) to install Gulp onto your computer. We'have add a -g flag to ensure Gulp is available globally for any project.

Verify that Gulp has installed the following command:
gulp -v
Like before, this should return the version number on the next line of your command-line.

Step 3: Navigate To Your Project Directory And Install Gulp Locally
Now that we have met our command-line interface and know how to communicate with it, our next step will be navigating to your project directory. This will likely be different for each person, but as an example this is what I would type to navigate to my local project:
Anup:~ anup$ cd /Applications/MAMP/htdocs/my-project
Once you have made it to your project directory - let's run a quick npm command to initialize our package.json file.
Anup:my-project anup$ npm init
This will prompt us to answer a few questions about our project. Once completed, it will create a file in the root directory of the project called package.json which will provide information about the project and its dependencies as shown in figure below:.


Once the package.json file is created, we can install Gulp locally into the project by using the following command:
Anup:my-project anup$ npm install gulp --save-dev
We've added --save-dev, which tells the computer to add gulp as a dev dependency in package.json as shown below.


If you check the project folder when the command has finished executing, you should see that Gulp has created a node_modules folder. You should also see a gulp folder within node_modules as shown below.


We're almost ready to start working with Gulp. Before we do so, we have to be clear on how we're going to use Gulp for the project, and part of that is deciding on a directory structure.

Next tutorial(Part 2), we will go through Directory Structure for the project and write the first GULP task.

Reference: https://css-tricks.com/gulp-for-beginners/
Automate Your Tasks Easily with Gulp.js
Getting Started with Gulp