Posts on this Category



Tutorial: Sorting and Filtering a ReactJS Datatable

ReactJS Datatable with Sort and Filter
ReactJS Datatable with Sort and Filter

A few months ago I’ve made this post about how to create a reactjs datatable using the FixedDataTable module, I didn’t cover much, I just gave a simple example explaining how to populate the table with JSON data. Today we’re going a little further, continuing from where I stopped I’m going to show you how to sort and filter the data on this datatable.

Before we begin I’ll reorganize the code a little bit, let’s put all our datatable related code in a different file, I’ll name it myTable.js, its content should look like this:

import React from 'react';
import {Table, Column, Cell} from 'fixed-data-table';
 
class MyTable extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      rows : [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
             "country":"Argentina","ip_address":"247.180.226.89"},
              {"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
             "country":"South Africa","ip_address":"27.146.70.36"},
              {"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
             "country":"Colombia","ip_address":"103.52.74.225"},
             // more data
    };
  }
 
  render() {
      return <Table
        height={40+((this.state.rows.length+1) * 30)}
        width={1150}
        rowsCount={this.state.rows.length}
        rowHeight={30}
        headerHeight={30}
        rowGetter={function(rowIndex) {return this.state.rows[rowIndex]; }.bind(this)}>
        <Column dataKey="id" width={50} label="Id" />
        <Column dataKey="first_name" width={200} label="First Name" />
        <Column  dataKey="last_name" width={200} label="Last Name" />
        <Column  dataKey="email" width={400} label="e-mail" />
        <Column  dataKey="country" width={300} label="Country" />
      </Table>;
  }
}
 
module.exports = MyTable;

I’m just making it because it’s a good practice, in this example it won’t make much difference, but in an application with multiple components it would get really messy if you put everything on the main.js.

After isolating the datatable component our main.js is much cleaner:

import MyTable from './myTable';
import React from 'react';
import ReactDOM from 'react-dom';
 
ReactDOM.render(<MyTable/>,document.getElementById('example'));

If you run the project now you should see the exact same result as before, now let’s start adding some features to this table.

Filtering the data

We have to make a few changes in the constructor in order to add the filter functionality:

constructor(props) {
  super(props);
  this.rows = //json data
  this.state = {
    filteredDataList: this.rows
  };
}

As you can see I took the rows variable out of the state and replaced it with filteredDataList, now you must think of rows as our data source, like a database table or a web service it shouldn’t be part of our state, what should be is the data we are actually displaying on the table, which will be the filteredDataList. Initially it will have the exact same data as the rows variable, but as the user starts filtering, its value will change.

After this, the attributes height, rowsCount and rowGetter of our table are still referencing the rows variable, as the table won’t interact directly with this variable anymore, they should be changed to reference the filteredDataList.

Now let’s add to our class the methods responsible for the filtering:

_renderHeader(label, cellDataKey) {
  return <div>
        <span>{label}</span>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}
 
_onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      filteredDataList: this.rows,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.rows.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.rows[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.rows[index]);
    }
  }
  this.setState({
    filteredDataList: filteredList,
  });
}

The _renderHeader() function tells the Column what should be rendered on it’s header, in this case it’s just adding an input so the user can type and filter the data, on its onChange event I’m calling the function _onFilterChange which will actually do the filtering and update the filteredDataList value.

Lastly we have to call the _renderHeader function on our columns like this:

<Column dataKey="id" width={50} label="id"  
     headerRenderer={this._renderHeader.bind(this)}/>

Note that I’ve used bind() to call the function _renderHeader(), it’s really important that you do exactly like that, otherwise you will come across the problem described here.

Now you can run your project, if you did everything right you should see an input bellow the label on the header, if you type something in there you’ll see that the filter is already working.

Making the Columns Sortable

In order to use the sort feature we have to add two more attributes to the state: sortBy and sortDir:

 
constructor(props) {
  super(props);
  this.rows = //json data
  this.state = {
    filteredDataList: this.rows,
    sortBy: 'id',
    sortDir: null
  };
}

The first is responsible for telling by which column our datatable is currently being sorted by, it’s being initialized with the column id, and the second is just for allowing us to control whether it’s ASC or DESC.

We also have to modify the _renderHeader() a little bit:

_renderHeader(label, cellDataKey) {
  return <div>
        <a onClick={this._sortRowsBy.bind(this, cellDataKey)}>{label}</a>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}

I just replaced the span with a link where the user will click to sort the table, on the onClick event it calls the following function:

_sortRowsBy(cellDataKey) {
  var sortDir = this.state.sortDir;
  var sortBy = cellDataKey;
  if (sortBy === this.state.sortBy) {
    sortDir = this.state.sortDir === 'ASC' ? 'DESC' : 'ASC';
  } else {
    sortDir = 'DESC';
  }
  var rows = this.state.filteredDataList.slice();
  rows.sort((a, b) => {
    var sortVal = 0;
    if (a[sortBy] > b[sortBy]) {
      sortVal = 1;
    }
    if (a[sortBy] < b[sortBy]) {
      sortVal = -1;
    }
 
    if (sortDir === 'DESC') {
      sortVal = sortVal * -1;
    }
    return sortVal;
  });
 
  this.setState({sortBy, sortDir, filteredDataList : rows});
}

This function is responsible for the sorting, if you take a look at the code you’ll see that in order to “decide” how the table should be sorted it uses and modifies the two new variables we added to the state, at the end it sets the state again with the modified values.

Now add this code to your render() function, right before returning your component:

var sortDirArrow = '';
if (this.state.sortDir !== null){
  sortDirArrow = this.state.sortDir === 'DESC' ? ' ↓' : ' ↑';
}

This code is just for controlling the arrow that will be displayed in front of the column label. Don’t forget to add the logic to your column label attribute as well, otherwise the arrow won’t be displayed.

<Column dataKey="id" width={50} 
  label={'id' + (this.state.sortBy === 'id' ? sortDirArrow : '')}
  headerRenderer={this._renderHeader.bind(this)}/>

Ok, now we are done with the sorting and filtering, if you run your project the result should be exactly the same as the gif at the beginning of this post.

That’s it! Hope you enjoyed the tutorial, just leave a comment if you have any doubts.

ReactJS Error: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

This is a very common error for reactjs beginners, if you are facing this error it means your render method is modifying the state of your component, causing it to re-render, which then will modify it again and so on. You are dealing with an infinite loop here, if you take a look at your console (before your browser crashes) you’ll see something like this:

setState(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
setState(…): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

Before I explain how to solve it I’ll show you the most probable reason why it’s happening, let’s analyze the following component:

class ErrorSimulation extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      x : 1
    };
  }
 
  _changeValue(newValue){
    this.setState({newValue});
  }
 
  render() {
    return <a onClick={this._changeValue(2)}>Change Value</a>
  }
}

Note that the render() method is calling the function _changeValue(), if you take a look at this function you’ll see that it’s modifying the state. Nothing wrong, right? This should be OK, otherwise how would the component be able to modify it’s own state? Well, the problem here is the way we call the function, by doing it like I did in this example the function _changeValue() will actually be called and executed right away during the state transition, this will cause the problem. We can solve that by changing a little bit the way we call the function.

Instead of doing this:

<a onClick={this._changeValue(2)}>Change Value</a>

we call it like this:

<a onClick={this._changeValue.bind(2)}>Change Value</a>

By using bind() your function won’t be called during the state transition anymore, it will complete the process and leave the function to be called later, this will prevent the problem from happening.

Angular2 Tutorial: Creating Custom Pipes

Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don’t meet our needs, that’s when we have to create custom pipes. This will be a very quick tutorial in which I’ll give you an example of how you can create your own pipes.

I’m assuming you already have your angular2 project, but if you don’t, just follow the instructions on the official site to create a starter project. Make sure the project is working before you proceed.

As an example I’m going to create a pipe to limit the amount of characters on a string, let’s assume you have limited space on your page and there is no way for you to display the entire text, you’ll just provide the maximum amount of characters and the pipe will take care of the rest, every time you come across this situation you can use this pipe to make the text fit on the space you have available.

Let’s start by creating in our app folder a file called maxLength.pipe.ts, copy/paste the following code into it:

import {Pipe} from 'angular2/core';
 
@Pipe({
    name: 'maxLength'
})
export class MaxLengthPipe {
    transform(val, args) {
        if (val.length > 30){
            return val.substring(0, 30)+'...';    
        }else{
            return val;
        }
    }
}

Perfect, you already have a pipe!! All you had to do was to create a class and put the @Pipe decorator on it, but to make it work we also have to implement the transform function, that’s where we are going to put our logic. In this simple example I’m just checking if my text has a length greater than 30, if it does I’m returning the first 30 characters.

That’s enough for us to be able to use our pipe, open your app.component.ts and paste the following code:

import {Component} from 'angular2/core';
import {MaxLengthPipe} from './maxLength.pipe';
 
@Component({
    selector: 'my-app',
    template: `<p>{{value | maxLength}}</p>`,
    pipes: [MaxLengthPipe]
})
 
export class AppComponent { 
    public value = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel dui '
                  +'at sem placerat dictum dictum placerat est. Mauris pretium mattis nulla '
                  + 'vel suscipit.Vestibulum laoreet congue erat, eget bibendum justarius id';   
}

That’s the simplest possible example, I have a class with just one attribute which will store my text. Note how I used the pipe in the template, I just wrote the name of my variable followed by the pipe name we specified in the @Pipe decorator, which in this case was maxLength.

If you run the project you’ll see that it’s already working, but we can improve it a little bit more, instead of always returning the first 30 characters, we can pass a parameter to the pipe telling how many characters we want. To do that we have to modify our transform function, everywhere we were using the number 30 we have to replace it by args[0], this is how it should look like:

transform(val, args) {
    if (val.length > args[0]){
        return val.substring(0, args[0])+'...';    
    }else{
        return val;
    }
}

Then in the app.component.js you can pass the parameter like this:

{{value | maxLength : 30}}

That’s it!! Hope you enjoyed the tutorial, leave a comment if you have any doubts.

Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns

In this tutorial I’m going to show you one of the datatable solutions available for Angular 2, it’s called ag-Grid and it’s available not only for angular2, but also for other frameworks like Angular 1 and React. It’s a really complete datatable, it has lots of features that I definitely want to explore in other tutorials, but in this one I’ll try to keep it as simple as possible, my goal is to just make it display the data and enable the sorting, filtering and the resizable columns features. Maybe in the future I’ll write a PART 2 of this tutorial explaining how to add some more complex functionality. If you don’t want to use ag-grid take a look at this post.

I’m assuming you already have your Angular 2 project ready, but if you don’t just follow the instructions on this link to set up your environment, it’s really easy and straightforward, all you need to do is to create three configurations files: tsconfig.json, typings.json and package.json, make sure you have all of them before you continue.

Now let’s add the ag-grid to the project, to do that you have to add these two lines to the dependencies list on your package.json:

{
  "dependencies": {
    "ag-grid": "3.3.x",
    "ag-grid-ng2": "3.3.x"
    ...
  },
}

Run npm install to download and install the dependencies, when it completes we’ll be ready to start writing some code!

Open your project folder and create another one inside called app, that’s where we’re going to put all our Angular2 related code. The first file we are going to create on this folder is the app.component.ts, it should contain the following code, just copy and paste it into the file:

import {Component} from 'angular2/core';
import {AgGridNg2} from 'ag-grid-ng2/main';
 
@Component({
    selector: 'my-datatable',
    directives: [AgGridNg2],
    template: `
         <ag-grid-ng2 #agGrid style="height:100%;width:845px" class="ag-fresh"
            [gridOptions]="gridOptions">
         </ag-grid-ng2 >
     `
})
 
export class AppComponent { 
    myRowData = [
        {"name":"Ronald Bowman","country":"China","city":"Lutou","email":"rbowman0@spotify.com"},
        {"name":"Pamela Hill","country":"Russia","city":"Krylovskaya","email":"phill1@symantec.com"},
        {"name":"Robin Andrews","country":"Ukraine","city":"Korop","email":"randrews2@photobucket.com"},
        {"name":"Peter Kim","country":"Mexico","city":"San Jose","email":"pkim3@theatlantic.com"},
        {"name":"Carol Foster","country":"Mexico","city":"El Aguacate","email":"cfoster8@intel.com"},
        {"name":"Jimmy Burke","country":"Indonesia","city":"Banjarsari","email":"jburke9@over-blog.com"},
        {"name":"Jonathan Crawford","country":"Peru","city":"Alca","email":"jcrawforda@deliciousdays.com"},
        {"name":"Donald Montgomery","country":"Poland","city":"Działoszyce","email":"dmontgomeryb@google.com.br"},
        {"name":"Donna Shaw","country":"Japan","city":"Akune","email":"dshawc@chronoengine.com"},
        {"name":"Helen King","country":"United States","city":"Hollywood","email":"hkingd@devhub.com"},
        {"name":"Walter Myers","country":"China","city":"a ndaowa n", "email":"wmyerse@state.tx.us"},
        {"name":" Alice Collins","country":"Papua Nw  Guine a", "city":"Mendi","email":"acollinsf@npr.org"},
        {"name":"Anne Richards","country":"China","city":"Koramlik","email":"arichardsu@vinaora.com"},
        {"name":"Randy Miller","country":"Indonesia","city":"Trenggulunan","email":"rmillerv@oakley.com"},
        {"name":"Phillip Adams","country":"Bahamas","city":"Duncan Town","email":"padamsw@lycos.com"},
        {"name":"Nicholas Allen","country":"Philippines","city":"Bautista","email":"nallenx@aboutads.info"},
        {"name":"Lisa Willis","country":"Thailand","city":"Lat Yao","email":"lwillisy@istockphoto.com"},
        {"name":"Jeffrey Castillo","country":"Indonesia","city":"Karangsari","email":"jcastilloz@washington.edu"},
        {"name":"Michael Carpenter","country":"Colombia","city":"Cali","email":"mcarpenter13@prlog.org"},
        {"name":"Roger Lee","country":"France","city":"Courtaboeuf","email":"rlee14@earthlink.net"},
        {"name":"Steve Wallace","country":"Russia","city":"Novobeysugskaya","email":"swallace15@cisco.com"},
        {"name":"Shirley Patterson","country":"Peru","city":"La Tinguiña","email":"spatterson16@woothemes.com"},
        {"name":"Nancy Ward","country":"Sweden","city":"Båstad","email":"nward17@mapquest.com"}
    ];
 
    columnDefs = [
        {headerName: 'Name', field: "name", width: 200 },
        {headerName: 'Country', field: "country" ,width:180},
        {headerName: 'City', field: "city" ,width:160},
        {headerName: 'e-mail', field: "email" ,width:300}
    ];
 
    gridOptions = [];
 
    constructor() {
        this.gridOptions = {
            rowData: this.myRowData,
            columnDefs: this.columnDefs,
            enableColResize: true,
            enableSorting: true,
            enableFilter: true
        }   
    }
}

There is quite a lot to explain about this code, I’m going to start with the class AppComponent, that’s where we’re going to put all the parameters and configurations that makes our datatable work, we have three variables on this class: myRowData, columnDefs and gridOptions.

myRowData: This variable will store the data to be displayed on the table, for this example I’m just going to use some JSON data I generated, but in a real case scenario you would get the data from your database or a web service.

columnDefs: This one will store an object containing information about every column of our datatable, I’m just using the attributes headerName to define the column title, field to tell which array attribute will be displayed on the column and width to define the size of each column. Although I’m using only three, there are tons of other attributes you could specify here.

gridOptions: This one just wraps everything up and make it available to the component. It’s being initialized empty, but in the constructor I’m setting its value, besides the rowData and columnDefs I’m also specifying the attributes enableColResize, enaleSorting and enableFilter. They will do exactly what their names suggests, enable the columns resize, sorting and filtering features respectively.

Now we can create our component, to be able to use the directive AgGridNg2 we have import it first with the line import {AgGridNg2} from 'ag-grid-ng2/main, after that all you need to do is to pass the gridOptions to the ag-grid-ng2 component on the template.

Before we write the index.html we’re going to need one more ts file to be able to launch our application, on your app folder create the file main.ts and paste the following code into it:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'
 
bootstrap(AppComponent);

Now you can create the index.html file on your project root folder, let’s take a look at the code:

<html>
  <head>
    <title>Datatable</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <link href="node_modules/ag-grid/dist/styles/ag-grid.css" rel="stylesheet" />
    <link href="node_modules/ag-grid/dist/styles/theme-fresh.css" rel="stylesheet" />
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          },        
          lib: {
            format: 'register',
            defaultExtension: 'js'
          },
          'ag-grid-ng2': {
            defaultExtension: "js"
          },
          'ag-grid': {
            defaultExtension: "js"
          }
        },
        map: {
            'ag-grid-ng2': 'node_modules/ag-grid-ng2',
            'ag-grid': 'node_modules/ag-grid'
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <my-datatable>Loading...</my-datatable>
  </body>
</html>

This file will basically be used just to load the necessary scripts and to configure SystemJS to load everything and launch the application. Finally you can use your component here calling it by the selector we specified before: my-datatable.

We’re done!! To run the project open your terminal, navigate to your project folder and run npm start, this should be the result: my-datatable.

Angular 2 Datatable with Sorting, Filtering and Resizable Columns
Angular 2 Datatable with Sorting, Filtering and Resizable Columns

Creating a Live Auction App with Angular 2, Node.js and Socket.IO

Angular 2 Auction App
Angular 2 Auction App

In this tutorial we’re going to build a very cool Live Auction Application, my goal is to demonstrate how Angular 2, Node.js and Socket.io work together, and as everyone knows Angular 2 will soon come out so I thought it would be great to write a tutorial involving it. Of course our app won’t have all the features a real auction app has, this is just an example to demonstrate how to integrate the frameworks I mentioned.

Setting up the Environment

The first step is to configure the environment, let’s get started by creating our Node.js project, I’m going to use express to do it, if you don’t have it open your terminal and run the command npm install express-generator -g to install, then you can create the project with the command expess {project name} (replace {project name} with your actual project name).

Now you have the basic project structure created for you, but we need to make some changes in order add Angular 2 and Socket.io to the project, first open your package.json and paste the following code:

{
  "name": "auction",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "postinstall": "npm run typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "start": "concurrent \"node ./bin/www\" \"npm run tsc:w\"",
    "typings" : "typings"
  },
   "license": "ISC",
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "angular2": "2.0.0-beta.6",
    "systemjs": "0.19.20",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.14",
    "socket.io":"1.4.5"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^2.0.1",
    "typescript": "^1.7.5",
    "typings":"^0.6.8"
  }
}

Now create another file called tsconfig.json in the project root folder and put the following into the file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Also in the root folder create the typings.json and copy/paste the following code into it:

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim
/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
  }
}

Ok, we have now created all the configuration files, but before we continue you have to install the dependencies by running the command npm install on the terminal.

If you open your app.js you’ll see that express has already put some code in there, in order to make it as simple as possible let’s delete the code we don’t need, after the modification your app.js should look like this:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
 
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
app.use('/', routes);
 
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
 
module.exports = app;

By default express sets jade as the view engine, we’ve already deleted the lines responsible for that in the app.js, but if you check the folder /views you’ll see some .jade files, you can delete them if you want, later we’re going to place our Angular 2 HTML pages in this folder, but for now you can just create and leave an empty index.html in there.

After getting rid of the .jade files we have to tell Node.js that we want to use our index.html instead, we can do that by changing a little bit the code in the routes/index.js file, just open the file and replace its content with the following code:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

To make sure it’s working run your project with the command npm start then enter the url http://localhost:3000/ in your browser, it should display an empty page, write something in the index.html you created and refresh the page, if it appears on the browser you’ve done everything right! Now we’re ready to actually start writing some code.

Introducing Socket.IO

As we know, an auction app must be real-time, which means that when a user places a bid all the other connected users must instantly see it, that’s where Socket.IO comes in, it allows Node.js to receive and broadcast events to all connected clients, so when a user places a bid Socket.IO will emit an event to the server which will update the product price and broadcast it to the other users.

Now let’s see how that looks like in code, copy the following code and paste bellow the var app = express(); in your app.js:

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
io.set("origins", "*:*");
 
var currentPrice = 99;
 
io.on('connection', function (socket) {
	socket.emit('priceUpdate',currentPrice);
	socket.on('bid', function (data) {
		currentPrice = parseInt(data);
		socket.emit('priceUpdate',currentPrice);
		socket.broadcast.emit('priceUpdate',currentPrice);
	});
});

In the first 5 lines I’m just creating the server that Socket.IO will use to send/receive events, then I’m creating a listener to the connection event which will be emitted every time a user connects (we’ll get to that in a moment), you can use the function io.on(event, callback) to create a listener to any event you want, you just need to pass the event as the fist argument and the callback function as the second, when it receives the event the callback will be executed.

In this case when a user connects I’m immediately emitting the event priceUpdate passing the current price, that’s because at this moment the client-side doesn’t have the current price yet, so that’s the first thing we want to send. After that we have to create a listener to the bid event that will update the price and broadcast to the other users. Note that I’m calling socket.emit() and socket.broadcast.emit(), the first one will return the updated price to the user that triggered the event, and the second will do the same to all the other users.

Writing our First Angular 2 Component

Now that we have our server-side ready we can get started with Angular 2, let’s create a folder called app inside public/javascripts/ on our project, that’s where we’re going to put all our Angular 2 code. Now create a file and name it app.component.ts, then paste the following code into it:

import {Component} from 'angular2/core';
 
@Component({
    selector: 'auction-app',
    templateUrl: 'templates/product.html'
})
 
export class AppComponent {
    price: number = 0.0;
    socket = null;
    bidValue = '';
 
    constructor(){
        this.socket = io('http://localhost:8000');
        this.socket.on('priceUpdate', function(data){
            this.price = data;
        }.bind(this));    
    }
 
    bid(){
        this.socket.emit('bid', this.bidValue);
        this.bidValue = '';
    }
}

When declaring a @Component, you have to pass an object containing two attributes selector and templateUrl (or just template), the selector is the name we’re going to use to call our component, in this case it’s auction-app, and the templateUrl is the HTML implementation, you can put your HTML code directly on the object or you can put it in a separated file like I did.

We also have in this code the AppComponent class, that’s kind of the ‘controller’ of our component, in the constructor I’m connecting to the Socket.IO from the server using the method io('http://localhost:8000'), this will emit the connection event we saw before, then I’m creating a listener to the priceUpdate event, the server will emit it right after the connection, remember? When Angular receives the updated price it will assign it to the price variable. This class also contains the bid() function, it will just emit the bid event passing the bidValue.

I forgot to mention that I created the /template folder inside /views, the problem is that our component doesn’t have access to it, to solve this problem we have to make this folder a static route on our server, open your app.js and add this line:

app.use('/templates', express.static(__dirname + '/views/templates/'));

Now let’s take a look on our template, I’ll not show the full HTML code here, just the lines that interact with our AppComponent class.

<h1>$ {{price}}</h1>	        
<input  [(ngModel)]="bidValue" >
<button (click)="bid()">Place Bid</button>

There is not much to explain here, the syntax resembles a lot the first Angular, our input uses the attribute [(ngModel)] to reference the bidValue variable from our class, and the button uses the (click) to call the function bid().

To be able to launch our application we have to create a file called main.ts on the public/javascripts/ folder, just copy/paste the following into the file:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component.js'
 
bootstrap(AppComponent);

Finally we can write our index.html, you have already created it in the beginning, remember? It’s located on the /views folder, open it and add the following code:

<html>
  <head>
    <title>Live Auction</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script> 
    <script src="scripts/es6-shim/es6-shim.min.js"></script>
    <script src="scripts/systemjs/dist/system-polyfills.js"></script>
    <script src="scripts/angular2/bundles/angular2-polyfills.js"></script>
    <script src="scripts/systemjs/dist/system.src.js"></script>
    <script src="scripts/rxjs/bundles/Rx.js"></script>
    <script src="scripts/angular2/bundles/angular2.dev.js"></script>
    <script src="javascripts/jquery.js"></script>
    <script src="javascripts/bootstrap.min.js"></script>
    <link href="stylesheets/bootstrap.min.css" rel="stylesheet">
    <link href="stylesheets/portfolio-item.css" rel="stylesheet">
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('javascripts/app/main.js')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <auction-app>Loading...</auction-app>
  </body>
</html>

Once again we have to edit the app.js file to be able to load the scripts directly from the node_modules folder, add the following line like we did before:

app.use('/scripts', express.static(__dirname + '/node_modules/'));

This file is pretty simple, we have a script that configures System.js to load our application, and in the body we can call our component by the selector we specified before: auction-app.

Now we’re done!! You can run your application by opening your terminal and running the command npm start, the result should similar to the gif in the beginning of this tutorial.

Just leave a comment if you have any problems, I’ll be glad to help!!

How to Execute a .jar File with Node.js Child Processes

You probably have already come across situations where your application had to execute other applications or native commands from the OS. Node.js can easily do that by spawning child processes. To show you how to do that I’m going to give you an example of how to execute a .jar file with node.

First let’s create a very simple java application for us to use in this example, this is the one I’m going to use:

package javaapp;
 
public class JavaApp{
 
    public static void main(String[] args) {
        System.out.println("This is the Java application output!!");
    }
 
}

This class is very simple but it will be enough to demonstrate how child processes work, just copy the code, compile it, and place the jar file into folder of your choice.

Now let’s create a js file containing the following code:

var exec = require('child_process').exec;
var child = exec('java -jar C:/javaApp.jar',
  function (error, stdout, stderr){
    console.log('Output -> ' + stdout);
    if(error !== null){
      console.log("Error -> "+error);
    }
});
 
module.exports = child;

Note how easy it is, first I required the module child_process and then I called the function exec() passing as an argument a native OS command to execute a java file, which is : java -jar C:/javaApp.jar. In the callback function I have 3 variables: error, stdout, stderr, but I’m going to use only the first two. The javaApp.jar output will be stored on the stdout variable, and the errors will be in the error variable, obviously.

To run this code just open the terminal, navigate to your js file location and execute the command:

node app.js

If everything is right you should see the output:

Output -> This is the Java application output!!

Saving your Neural Network Training Progress

If you are familiar with Neural Networks you know that training one is very time consuming, it can take days, weeks or even months, the time will depend on the purpose of your application and the hardware you have available. But regardless of the time, you don’t want to lose the progress after training your neural network, otherwise you would have to train it again every time you run your application.

In this tutorial I’m going to show a very easy way to store and load your network data. I’m going to use Encog Framework from Heaton Reasearch, it’s a great machine learning framework, if you don’t know it yet, it’s definitely worth checking out.

So let’s get started, if you are reading this tutorial you probably already have your network ready, but for those of you who don’t, here is an example of how to create one:

BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(null, true, 2));
network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 2));
network.addLayer(new BasicLayer(new ActivationSigmoid(), false, 1));
network.getStructure().finalizeStructure();
network.reset();

This is a really simple one, I’m not going to explain the details about this code because that’s not what this tutorial is about, but I promise I’ll write another one explaining more about it.

Now let’s suppose you spent hours training it and you don’t want to lose everything, you can solve this with just one single line of code, here is how you can save the progress:

EncogDirectoryPersistence.saveObject(new File("C:/networkData.eg"), network);

It couldn’t be easier than that! Basically, the only thing you have to do is to pass the path, the file name and the network to the EncogDirectoryPersistence.saveObject method, it will generate and save for you an .eg file containing the network data. If you check the folder after executing this line the file will probably be there.

Loading that file is equally easy, instead of creating your network like did in the example above, you just have to do call the method EncogDirectoryPersistence.loadObject passing the file you want to load, like this:

BasicNetwork network = (BasicNetwork) EncogDirectoryPersistence.loadObject(new File("C:/networkData.eg"));

That’s it! I’ve just recreated my network with the data I saved before, now I could train it a little bit more and then save it again overriding the same file.

Hope you liked the tutorial, leave a comment if you have any doubts, I’ll be very happy to help!

AngularJS Internationalization Example

Today I’m going to give you a very simple example of how to translate a AngularJS page with the module angular-translate. To illustrate how to do that, I’m going to create a login screen with 3 or 4 labels, then I’ll make them available in two different languages: English and French. If you need more languages you just have to follow the same principle.

The first thing we need to do is to provide the texts in both languages to our application, we can easily do that in the module.config function, let’s take a look at the code, this will be our app.js file:

var app = angular.module('angularjs_internationalization',['pascalprecht.translate']);
 
app.config(function($translateProvider) {
  $translateProvider.translations('en_US', {
    TITLE: 'Login Form',
    USERNAME: 'Username',
    PASSWORD: 'Password',
    LOGIN: 'Login'
  });
 
  $translateProvider.translations('fr_CA', {
    TITLE: 'Formulaire de login',
    USERNAME: 'Identifiant',
    PASSWORD: 'Mot de passe',
    LOGIN: 'Connexion'
  });
  $translateProvider.determinePreferredLanguage();
});

I just declared the two languages using the function translations() from the translateProvider service, it receives the language key as the first argument and an object containing the texts as the second, note that related texts have same ID in both objects, it won’t work if you use different IDs. After that I called the function determinePreferredLanguage() which tells AngularJS to choose the most suitable language for each user, you can also pick a language by hand, I’ll tell you how to do that in a moment.

Next, we need to create the HTML page, just copy the following code and paste into your index.html file:

<html ng-app="angularjs_internationalization">
<head>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js" />
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.9.0/angular-translate.min.js" />
	<script src="app.js" />
	<link href="style.css" rel="stylesheet" type="text/css"  />
	<title translate>TITLE</title>
</head>
<body>
	<div class="loginpanel">
	  <div class="txt">
	    <input id="user" type="text" placeholder="{{'USERNAME' | translate}}" />
	    <label for="user" class="entypo-user"></label>
	  </div>
	  <div class="txt">
	    <input id="pwd" type="password" placeholder="{{'PASSWORD' | translate}}" />
	    <label for="pwd" class="entypo-lock"></label>
	  </div>
	  <div class="buttons">
	    <input type="button" value="{{'LOGIN' | translate}}" />
	  </div>
	</div>
<span class="resp-info"></span>
</body>
</html>

You don’t need to be concerned about every single line of this code, what matters here is just how we call our texts from the angular module, which is very simple, as you can see in the placeholder attribute of both inputs, you just need to call your text ID followed by the filter translate.

Now if you run you project you should see the page in your browser’s default language:

Login Form in English
Login Form in English

If you want to test the other language as well, instead of calling the determinePreferredLanguage() function at the end of the config() method, you have to call preferredLanguage() passing the language you want:

$translateProvider.preferredLanguage('fr_CA');

And this should be the result:

Login Form Translated
Login Form Translated

That’s it guys! Thanks for reading this tutorial, just leave a comment if you have any problems, I’ll be glad to help!

AngularJS Tutorial: Conditional Render Example

As a web developer I can say that everyone that works with web development, no matter the language, comes across conditional rendering very often (almost every day), it’s pretty much impossible to see a project that doesn’t have a UI component that cannot be shown if a specific condition isn’t true. And that is not different for AngularJS developers, so today we’re going to learn how to do it with AngularJS, this will be a very simple and easy tutorial, if you are just getting started with angularjs this is the right tutorial for you.

So let’s get started, the example I’m going to give consists in an application with a button that will be responsible for showing and hiding a div that contains some content, to make that content visible and invisible we’re going to use conditional rendering, pretty straightforward, right?

We’re going to start by creating the app.js file, here is how it should look like:

var app = angular.module('renderExample',[]);
app.controller('renderExampleController', function($scope){
	$scope.showContent= true;
	$scope.label= 'Hide Text';
 
	$scope.switch = function(){
		if($scope.showContent){
			$scope.showContent= false;
			$scope.label= 'Show Text';
		}else{
			$scope.showContent= true;
			$scope.label= 'Hide Text';			
		}
	}
});

As you can see, I’ve declared two variables in my controller: showContent and label. The first one, as the name suggests, is the condition to render the content, it will only appear on the page when this variable is set to true, and the second one is the text that will appear in the button, when the content is visible the label will be 'Hide Text', and when it’s invisible it’ll be 'Show Text'. Lastly, we have the function switch() which will be called by the button and will be responsible for switching the content visibility by changing the two variables values.

Now the last thing we need to do is to create the index.html file:

<!DOCTYPE html>
<html ng-app="renderExample">
   <head>
      <title>Conditional Render Example</title>
      <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
      <script src="app.js"></script>
   </head>
   <body>
      <div ng-controller="renderExampleController">
         <input type="button" value="{{label}}" ng-click="switch()"/>
         <br />
         <div ng-if="showContent">
            Some content.
         </div>
      </div>
   </body>
</html>

You should be familiar with most of this code, what really matters here is the directive ng-if, this is the directive that controls if the component will be rendered or not, you just need to pass the condition, which in this case is the variable showContent.

That’s it!! Now if you execute your project you should be able to show/hide the text by pressing the button.

Tutorial: Integrating AngularJS with NodeJS

Integrating AngularJS with NodeJS
Integrating AngularJS with NodeJS

I know this tutorial may seem a little bit too basic for a lot of you, but these are two of the most popular javascript frameworks at the moment, as a result of that there are lots of people just getting started with NodeJS and AngularJS, and it’s a very common to see people asking how to integrate both, so this will be a very simple beginner level tutorial in which I’ll give an example to demonstrate how AngularJS and NodeJS can work together.

I’m assuming you have already set your enviroment, so we are going to start by creating our NodeJS project, to do that I’m going to use express, if you don’t have it yet just install via npm with the following command line:

npm install express-generator -g

With express installed simply navigate via terminal to the folder you want your project to be located and execute the command express passing your project name as a parameter, like this:

express myNodeProject

Now that your project is created, you can open it with the text editor of your choice, I’m going to use Sublime Text for this tutorial. When you do it you’ll see that express has already created the basic project structure for you:

Folder Structure
Folder Structure

By default, express uses Jade as the view engine, as you can see in the views folder we already have some jade files, which we are not going use, you can get rid of them later if you want. We’ll need to make some changes here to be able to use angularjs. Let’s begin by opening the file routes/index.js, it contains the following code:

var express = require('express');
var router = express.Router();
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
 
module.exports = router;

That’s the code responsible for rendering and redirecting to the index.jade file, what we need to do here is to change it a little bit and make it redirect to our angularjs index.html file (which we are going to create in a moment). After the changes the code should look like this:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

Now we need to create our index.html file, I’m going to put it in the views folder with the jade files. This is how my HTML code looks like:

<!DOCTYPE html>
<html ng-app="angularjsNodejsTutorial">
    <head>
        <title>Integrating AngularJS with NodeJS</title>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="javascripts/app.js" type="text/javascript"></script> <!-- not created yet -->
    </head>
    <body >
        <div ng-controller="myController">
        </div>
    </body>
</html>

In this file you can use not only AngularJS, but any javascript library you want, if you run your project you’ll see that nodejs is already redirecting to this file, you can now create you angularjs module and start writing some angularjs code as usual.

At this point you are already using angular and node in your application, but they are kind of independent from each other, there are no communication between them. To finish up this tutorial I’m going to show how AngularJS can make a request to NodeJS. But before we do that, we need to come back to the index.js file (the one we just modified) and create a function to return some data, which will be called when we make the request from our angularjs controller, just copy the following code and paste it right above the module.exports on your index.js.

router.get('/data', function(req,res){
	res.json([{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
        {"id": 2, "name": "Skyble", "city": "Guilmaro"},
        {"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
        {"id": 4, "name": "Realcube", "city": "Jrashen"},
        {"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
        {"id": 6, "name": "Jayo", "city": "Obonoma"},
        {"id": 7, "name": "Cogidoo", "city": "Sungsang"},
        {"id": 8, "name": "Avavee", "city": "Diawara"},
        {"id": 9, "name": "Tagtune", "city": "Monywa"},
        {"id": 10, "name": "Centimia", "city": "Retkovci"}]);
});

What is happening here is that the router.get function is assigning a function to the url ‘/data’, so when the user types ‘/data’ in the browser, node will call this function, which is doing nothing more than returning a json, it could be getting and handling data from the database, but as I want to keep it simple, a static json will do the job.

Now let’s create our app.js file, as you can see in the HTML code, it’s already referenced there. I’m going to put it on the public/javascript folder.

var app = angular.module('angularjsNodejsTutorial',[]);
app.controller('myController', function($scope, $http) {
    $scope.data = [];
    var request = $http.get('/data');    
    request.success(function(data) {
        $scope.data = data;
    });
    request.error(function(data){
        console.log('Error: ' + data);
    });
});

This is also a very straightforward code, I’m using the function $http.get with the argumentet ‘/data’ to make the request, then I’m assigning the result to $scope.data.

Now we just need to modify a little bit our HTML to make it iterate over our data and show it on the screen, just add this to the div with the ng-controller:

<ul ng-repeat="item in data">
	<li>Name: {{item.name}}, City: {{item.city}}</li>
</ul>

That’s it!! Now just run your project by executing npm start on the terminal and you’ll be able to access the application on your browser by typing localhost:3000, if you did everything right you should see a page with the data from our json.

Hope this tutorial was helpful, till the next one!!