Share Tweet Reccomend

Native JavaScript Promises

Promises are awesome and the new native promise JavaScript implementation is great and pretty much entirely across all modern browsers. In the past developers used various different promise libraries like jQuery.Deferred() or Q. However, with the native Promise now in JavaScript in most if not all environments, these are no longer really needed.

Below are 2 different examples of how you could use the native Promise object in JavaScript implementationwise…

//2 different examples of promise usage.  
jQuery(document).ready(function() {  
    
    var test = [];

    function getPost(id){
        var def = new Promise(function(resolve, reject){
            jQuery.ajax({ 
                url: "http://jsonplaceholder.typicode.com/posts/" + id,
                type: "GET",
                dataType: "json",
                success: function(data){
                    test.push(data);
                    resolve(data)
                },
                error: function(){
                    reject();
                }
            }); 

        });

        return def;
    }

    // Implementation #1
    getPost(1).then(function(data){
        console.log(data);
        return getPost(2); 

    }).then(function(data){
        console.log(data);
        return getPost(3); 

    }).then(function(data){
        console.log(data);

    }).catch(function(error){
        console.log('Sorry an error ocurred!');
        def.reject();
    });   

    // Implementation #2
    var arr = [getPost(1), getPost(2), getPost(3)]
    Promise.all(arr).then(function(values){
        console.log(values);
    });


});

Good stuff!

Share Tweet Reccomend

To Do: Create Your First React Application – Part II

Previously, we looked at getting set up creating a React “to do” application by installing our Node.js driven build tools and laying out some introductory components of code. In what follows we will continue on where we left off.

Adding “To Do” Items & Handling User Input

So far we have just looked how to display our components. Rendering data out to our page is all well and good, but to make our application truly dynamic we are going to need to implement a way to add and remove items to and from our list as well as edit them should we need to make any changes to any of the properties. So let’s update the code in TodoList.js to the following…

import {react} from 'react';
import {Todo} from './Todo';

export class TodoList extends React.Component {
    
    constructor(){
        super(...arguments);
        this.state = {
            todos: this.props.data,
            addTodoTitle: '',
            addTodoSummary: ''
        }
    }
    
    addTodoTitleChange(e){
        this.setState({
            addTodoTitle: e.target.value
        });        
    }
    
    addTodoSummaryChange(e){
        this.setState({
            addTodoSummary: e.target.value
        });           
    }    
        
    addTodo(){
        this.state.todos.push({
            id: this.state.todos[this.state.todos.length - 1].id + 1,
            title: this.state.addTodoTitle,
            summary: this.state.addTodoSummary,
            done: false
        });

        this.setState({
            todos: this.state.todos,
            addTodoTitle: '',
            addTodoSummary: ''
        });        
    }
    
    render() {
        
        var items = this.props.data.map((item, index) => {
            return (
                <Todo key={item.id} title={item.title} summary={item.summary} completed={item.done} />
            );        
        });
        
        return(
            <div>
                <ul>{items}</ul>
                
                <h3>Add New Item:</h3>
                <label>Title</label> <input type="text" value={this.state.addTodoTitle} onChange={() => this.addTodoTitleChange()} />
                <label>Description</label> <textarea value={this.state.addTodoSummary} onChange={() => this.addTodoSummaryChange()}></textarea>
                <button onClick={() => this.addTodo()}>Add New Item</button>
            </div>
        )
    }
};

So let’s discuss what is going on here. We have added 2 new values to our initial state object and we have created a form that will allow us to add a new “to do” item to our list. When we enter text into these fields the functions to update the state will run and we will update these values with setState by getting the current value of the form element we are editing off of the event that is passed into the function (e.target.value). Once we have filled out the form with the title and summary of the new item that we want, we can click the “Add New Item” button which, as we can see from our “onClick” handler, will run the “addTodo” function. If we look at this function we can see the code that we will need to add a new item to our list. Recall that we have to give each individual item an id and no two items can have the same id. So to generate a new id we will look at what the id value of the last item in our array is and just add 1 to that. That is an easy way to ensure that the new items that we add are always unique. We get the title and the summary from this.state which we have been setting in our text input handler functions. Lastly, we just set the initial value of the “done” flag to false since adding a new to do to the list is presumably not done yet. All of this data is passed into the common JavaScript Array object’s “push” method. We then update the state of our “todos” and then clear out the input text box and textarea in our form to get them ready to receive another value.

So build your code with $ webpack (or whatever task runner you are using) and try it out. You can see how we can now add new items to our list! Pretty slick!

Improving Our Code

Our example above works but you may have noticed something problematic with our implementation. We have individual handler functions for the two text elements in our “Add New Item” form. We also have separate properties that we use for setState. This is fine for this simple example, but what if we had a component with many different properties and values with many different fields that needed to be filled out? If we were to take the same approach as our example above, we would have to create an individual function for each and every property. Not too efficient!

Read More »

Share Tweet Reccomend

To Do: Create Your First React Application – Part I

React is a JavaScript library that is primarily responsible for handling the “view” component of a JavaScript single-page application. As it describes itself of the React homepage…

Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.

React’s focus, first and foremost, has to do with rendering dynamic UIs in a manner that is visually appealing to the user. It is flexible enough that it can be used in a diversity of capacities and contexts. We have looked at React in previous entries. In what follows we will look at creating an introductory application using React and React related tools and libraries. One of the more ubiquitous tutorial applications that developers build when learning a new language or framework is the TO DO (To do) app. In terms of prevalence, it is probably second only to the “Hello, World” app which has been around since the dawn of programming. But the “To Do” application is popular because it covers a lot of the basics of how a language or framework handles a number of things. There must be a way to add a new “to do” so handling user input is involved. The same is true for displaying data, editing and saving data, and changing display state when data updates. All of these things are going to be important implementations in any application.

In what follows we will create the iconic “To Do” application in React and discuss some of the inner workings as we go along. We will take a deeper look into React components and how we can add some dynamic interactivity to our React applications in response to user actions — things like clicks and entering text in a text box — and updating our views accordingly.

JSX Compilation with Babel & Browserify

As we will see, React has its own programming language called JSX. It has been described as sort of like a mixture of JavaScript and XML and it is React’s own special easy-to-read abstracted syntax. JSX is not required to create React applications and you can write your React components in native JavaScript if you prefer. Because browsers do not natively understand JSX in order for your react application to run JSX needs get converted to native JavaScript.

The React website suggests that you utilize tools like Babel and/or Browserify (both of which run on Node.js). Babel is what is known as a transpiler. It mostly functions as a tool that takes code written in ECMAScript 6 (ES6) and converts it to ES5. As of 2015 this is still necessary because support for ES6 across all browsers is not widespread yet. Until support for ES6 is implemented across all browsers, tools like Babel will still be needed. Although many people think of Babel primarily as an ES6 to ES5 transpiler, Babel also comes with JSX support as well. You can merely run the Babel transpiler on your JSX files and they will be converted to native JavaScript that will be recognized by any browser circa 2015.

Browserify allows for Node.js style module loading in your client-side JavaScript. Like with Node, it allows you to import code in certain JavaScript files into other JavaScript files for better organization of your code.

Task Runners / Module Bundlers

For our sample code, we will be using task runners to handle our JSX conversion to native JavaScript. You may have heard of task runners like Grunt or Gulp, or module bundlers like webpack. We will be using webpack because it has, at least for the time being, become the utility of choice among the React community. If you are not entirely familiar with JavaScript task runners it would definitely be worthwhile to read the webpack documentation (or watch a few videos) on what it is and why you would want to use it. The more recent versions of React essentially require you to set up your tools before you work with JSX in React. In previous versions of React there was an easy extra <script> tag that you could add in your HTML to make it easy to implement JSX. However this has since been deprecated. If this seems daunting and you are already feeling overwhelmed, not to worry! We will walk through how to set everything up before we dive into React coding.

Setting Up

To start we need to set up our package.json and webpack.config.js files so that we can set up our tools to do JSXcompilation to native JavaScript. Create a new directory and then create a package.json file and add the following…

{
    "name": "React",
    "version": "0.0.1",
    "description": "A React application...",
    "license": "MIT",
    "repository": {
        "type": "",
        "url": ""
    },
    "homepage": "http://www.9bitstudios.com",
    "scripts": {
        "start": "webpack-dev-server --progress"
    },    
    "dependencies": {
        "react": "15.3.0"
    },
    "devDependencies": {
        "webpack": "1.13.1",
        "webpack-dev-server": "1.14.1",
        "babel-core": "6.13.0",
        "babel-loader": "6.2.4",
        "babel-preset-es2015": "6.13.0",
        "babel-preset-react": "6.11.1"
    }
}

Next, in this same directory, create a webpack.config.js file and add the following…

var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    entry: __dirname + "/src/App.js",
    output: {
        path: __dirname + "/dist",
        filename: "App.js"
    },
    watch: true,
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',
                query:{
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    devServer: {
        colors: true,
        inline: true
    },     
    plugins:[
        new webpack.optimize.UglifyJsPlugin(),
    ]
};

After this, let’s open a command prompt and run the following…

$ npm install

to install all of our modules that we will need for compiling ES6 and JSX. And that is all there is to it. Now that we have our tools installed and configured, we can dive into writing our application.

Writing a “To Do” Application

So let’s get started creating our “To Do” app. We will start out by creating our index.html file…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div id="content"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
    <script type="text/javascript" src="dist/App.js"></script>      
    
</body>
</html>

As we can see, we are going to include App.js, which will be a file that we generate in our task runner. Note too we are creating a

with the id of “content.”

Next, create a folder called “src” and create a file called App.js in this folder. For this tutorial we are going to be breaking our components up into different modules so in our App.js file all we need to add for now is the following.

import {react} from 'react';

In the same directory as your App.js file, next create a file called “Todo.js”. In this file, we are going to need to create a React component/class that will represent each individual “to do.” Add the following code to this file…

import {react} from 'react';

class Todo extends React.Component {
    
    render() {
        return(<div>I am a to do</div>)  
    }
};

Pretty straightforward. This should look familiar as it is similar to our other earlier examples.

Now what we’re going to do is import this module into our App.js file. How do we do this? In our App.js file we just need to add the following…

import {react} from 'react';
import {Todo} from './Todo';

This will tell our code to import the “Todo” module from the “Todo” file relative to where “App.js” is located. With module loading in ES6 you can omit the “.js” from the file when you are importing modules.

So we are definitely well on our way but if we were to run this code as it is right now we would get an error. Why is this? Well, because we are importing a module from our “Todo.js” file we need to specify what this file exports. To do this we need to add the “export” keyword in front of what we want to make available from the “Todo.js” file. Thus, we need to change our code in our “Todo.js” file to the following…

import {react} from 'react';

export class Todo extends React.Component {
    
    render() {
        return(<div>I am a to do</div>) 
    }
};

Notice how we have added the “export” keyword in front of our class. Now there is something that can be imported from the “Todo.js” file. We will get into more complex combinations of what various files can export and import later on, but for now this simple example shows the basic setup of how it is done.

Now in our App.js file add the “render” method so we can confirm that everything is working…

 import {react} from 'react';
import {Todo} from './Todo';

ReactDOM.render(<Todo />, document.getElementById('content'));

Let’s build our App.js file by running “webpack” by opening up a terminal window typing the following…

$ webpack

Doing the above will build the App.js file and place it in our “dist” folder. Now if we open up another terminal window and run our server with…

$ npm start

and we go to http://localhost:8080 in our browser, if all has gone well we should be able to see the text “I am a to do.”

Component Composition

For our application we will be rendering a list of “to do” items inside of our “to do” list. Thus, we will also need to create a component that represents our “to do” list. So create a “TodoList.js” file in the same directory as the others and add the following code…

import {react} from 'react';
import {Todo} from './Todo';

export class TodoList extends React.Component {
    
    render() {
        return(<div>To do list here...</div>)  
    }
};

“TodoList” is the component that will serve as our “root” container component for our React application. It is just returning some placeholder text for now, but we will be adding more complexity to it very soon. Because the “TodoList” top-level component for this particular application, it is this one that will be the one that we want to render in our App.js file (not the individual “Todo” components). So change the code in our App.js file to the following…

import {react} from 'react';
import {TodoList} from './TodoList';

ReactDOM.render(<TodoList />, document.getElementById('content'));

Notice now how we are now rendering the “TodoList” component now and not the “Todo” components.

Read More »

Share Tweet Reccomend

ECMAScript 6 Arrow Functions

Arrow functions, also sometimes called “fat arrow” functions, are a new ES6 syntax for writing anonymous function expressions. We have looked at working with ES6 in previous entries about classes and module loading. (a.k.a the “next version of JavaScript”). A function expression in JavaScript refers to the notation where a developer sets a variable equal to a function like so…

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

Note that a function expression is different from a function declaration which would look like the following…

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

So arrow functions are primarily centered around function expressions. They have 2 main purposes. For one, they provide a more concise syntax which is a nice thing to have and can make code more readable. If were to take our function expression above and rewrite it as an arrow function, it would look like the following…

var sum = (a, b) => a + b; 

As can be seen here, this syntax looks a bit different from our original function expression. We have the arrow pointer pointing a statement that has omitted the { } from encapsulating the function body and we have omitted the “return” statement. In the above arrow function these things are implied. If we wanted to we could include these things and the meaning of the function would be the same.

var sum = (a, b) => { return a + b };

There are few rules around the syntax of arrow functions to watch out for. If there is only one argument in an arrow function the parenthesis do not need to be included. So an arrow function that simply returns “a” could be written like so…

var getVal = a => a;

However if the arrow function takes no arguments, parentheses must be used…

var getVal = () => "Hello world!";

Another interesting case of arrow function syntax is returning an empty object. The following results in an error…

var getVal = () => { };

The compiler sees this as having nothing in the function body and does not know what to return. As a result when returning an empty object you have to do the following…

var getVal = () => ({ });

So as we can see, arrow functions give us a much more terse way of writing code, allowing for a more readable concise syntax. This becomes useful in cases when using functions that have callbacks involved as arguments. Many functions that that perform asynchronous operations with data have this format. The following asynchronous promise style function…

getData().then(function (data) {
    return data;
});

Could be rewritten as the following using arrow functions…

getData().then(data => data);

It is pretty apparent that the second example is a lot more compact. As the number of functions like these get chained together, it can make the code a lot easier to read once you get used to the syntax.

Another and perhaps a more important aspect arrow functions is that they handle the scope of the “this” pointer within the function in a different manner. In other words, in arrow functions “this” points to the scope of the parent environment that the arrow function is contained within. This is a very important distinction. Arrow functions do not create their own “this” as normal functions do. A side-effect of this is that you cannot instantiate an arrow function with the “new” keyword as you can with normal functions because arrow functions have no internal prototype property.

Why were things done this way in ES6 and why is this useful? This can be very useful because you now no longer have to use apply, call, or bind to bind to the parent scope. One of the more common uses of the bind method within JavaScript applications is to pass the parent scope downward as you go multiple levels deep within methods within in object literal. For example, let’s say we had the following very general “actionClass” object literal. A lot of JavaScript applications use this pattern as an implementation…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){
            // we will set events here...

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

As we can see we are calling the actionClass.init() method which will set up some event handlers. So let’s add an event (using jQuery) where when we click an element we call another one of the methods within our actionClass object.

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            jQuery('.button').on('click', function(){
                this.doSomething();
            });

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

This code does not work. When we try to click the div we get an error in our console…

Uncaught TypeError: this.doSomething is not a function

Why is that? Well it is because the callback function for the click event has its own scope. “this” is now pointing at the function it is being called from. One way that developers solve this is by setting a variable to the parent scope. The following code works…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            var self = this;

            jQuery('.button').on('click', function(){
                self.doSomething();
            });

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

This is certainly a viable option and works fine for our simple example. However, as we go deeper and get more complex into multiple levels of nested functions with events or getting data asynchronously via AJAX requests or any number of other possibilities the process of constantly assigning variables to the scope that you want can get kind of messy. So what other approach can we take? This is where bind comes into the picture. We could also do something like the following…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            jQuery('.button').on('click', function(){
                this.doSomething();
            }.bind(this));

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

Simply by attaching .bind(this) after our function closing bracket } we are changing the scope of the function. We longer need to say var self = this;

But with arrow functions we can accomplish the same thing without having to resort to using “bind.” We can rewrite the above in the following manner (assuming we had ES6 compatibility in the browser or we transpiled the code)…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            jQuery('.button').on('click', () => {
                this.doSomething();
            });

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

Now because we have used an arrow function, the “this” pointer is set to the parent scope because of how arrow functions bind the lexical “this” to the parent. It may take a bit of getting used to but overall the differing scope of the “this” pointer combined with the concise syntax can make code that makes use of arrow functions a lot more readable and maintainable. We will be making use of them to some degree in upcoming examples, so it was necessary to at least introduce what arrow functions are and what they do.

This is just a brief look at a couple of the newer features found in ES6. Hopefully you found it helpful.

Share Tweet Reccomend

ECMAScript 6 Module Loading

In the past we had looked at working with classes in ECMAScript 6, the “next version of JavaScript.” Another component of ES6 that you will find prevalent is module loading. These are basically the same conceptual implementation of modules that you will find in Node.js. Modules in ES6 solve the problem of scope and dependency management. In the past with ES5 a variable or function just declared in the open — whether in a script block in an HTML file or in an external .js file — like so….

function sayHi(name) {
    return "Hi, " + name;
}

would be considered to be bad practice because you were polluting the global object (which is often the window object in the context of the web). As the size and complexity of your application grew the maintainability of it would become a lot more difficult because you would have to worry about potentially overwriting other variables and functions later on in your application if you happened to name them the same or accidentally assign them a value that you did not intend to. Because of this, you often saw applications “namespace” the various methods and variables of an application to objects like so…

var app = app || {};
app.greeting = {
    sayHi: function (name) {
        return "Hi, " + name;
    }
};

to avoid polluting the global object.

With ES6 modules, however, all of this becomes unnecessary. You can declare functions and variables freely and the scope is always local to that file unless explicitly specified as a global object. This makes managing scope and maintaining your application a lot easier.

If you have ever done any development with Node.js, you should be somewhat familiar with modules as it follows a particular form and structure known as the CommonJS module loading syntax. Basically the idea is that you can import various functions and methods from other JavaScript files into your own JavaScript file by using the “import” keyword. You reference the path to the file you are loading as a module from the location of the file you are importing your module(s) into. So let’s say in your project you had a file called “greeting.js” that lived in a folder named “lib” with the following code in it

export function sayHi(name) {
    return "Hi, " + name;
}
export function sayHello(name) {
    return "Hello, " + name;
}
export function sayHey(name) {
    return "Hey, " + name;
}

The “exports” keyword means that these functions are exported and can be imported into other JavaScript files. For example, in the root of your project (one level up from the “lib” directory) let’s say you had a file called main.js. In that file you could do the following…

import * as greet from 'lib/greeting';

console.log(greet.sayHi('Joe')); // "Hi, Joe"
console.log(greet.sayHello('Sally')); // "Hello, Sally"

Here we are importing all of the exported functions in the greeting.js file into a variable called “greet” using the * wildcard locally to our main.js file. If there were any other exported functions or properties in our greeting.js file, this would be available in main.js as well.

There are other syntaxes that can be utilized in module importing. For example, if we only wanted the sayHi and sayHello methods imported from our greeting.js file (and we did not want or need the sayHey method for some reason) we could do the following in main.js…

import { sayHi, sayHello } from 'lib/greeting';

console.log(sayHi('Joe')); // "Hi, Joe"
console.log(sayHello('Sally')); // "Hello, Sally"

There are other variations on the importing syntax and implementation as well that we might see as we go along. The main point is that this gives you a lot of flexibility in how you structure your application. Doing all of this is not too dissimilar from the importing that you would so in Java…

import com.domain.package;

or C#

using System.Net;

The difference being that in JavaScript you import from the path to the file and in Java and C# the packages are compiled into memory and imported from there. But in all cases the approach serves the same purpose.

You could also use the require syntax (again familiar from Node.js) to import a module…

var greet = require('lib/greeting.js')

console.log(greet.sayHi('Joe')); // "Hi, Joe"
console.log(greet.sayHello('Sally')); // "Hello, Sally"

The choice is yours depending on which you prefer.