Share Tweet Reccomend

Develop Apache Cordova Applications with HTML5 & JavaScript

In a prior discussion we looked at how to set up a project so that we could develop an Apache Cordova application using HTML5 and JavaScript. In that section we mostly covered how to set up, build, and run the project — which consisted of the same application in the www folder that Apache Crodova bootstraps when you create a new project. In what follows we will look at the approach for actually writing own code for our app and will look at how an app in Apache Cordova gets initialized. We will also look at how we can extend the Apache Cordova platform by using plugins to give ourselves additional features and functionality that will make for an all around better user-experience (UX) for the users of our app.

Now that we have our project set up and all our platforms added all that we have left to do now is create our application by creating what basically amounts to a website that runs HTML and JavaScript in the “www” folder. How should one develop for Apache Cordova? Personally, I would delete all of the boilerplate files and folders and start from scratch. That is what we will do here. Just take a quick note of how things are referenced in the index.html file and do the same for your own files.

In doing this, I have modified the index.html file in the “www” folder to the following…

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Cordova Application</title>
    </head>
    <body>
        
        <div id="main">Initializing...</div>
        
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

Note: Do not worry about that “cordova.js” reference or the fact that this file is nowhere to be found in our “www” folder. Apache Cordova will utilize this in the proper context when the app runs (so leave it in there).

So as far as the index.html goes, there is nothing too fancy. I have a css file (index.css) and a js file (index.js). That is all you need to get started.

Next, let’s look at our JavaScript in the index.js file. There is really only one thing you need to make note of when you develop Apache Cordova applications in JavaScript. There is a special event that Apache Cordova uses to tell the platform that the everything is loaded and the device you are using is ready to start running JavaScript in your Cordova application. This is what is known as the “deviceready” event. It only fires when you are running an app within a Cordova context (i.e. on a device or an emulator of a device). In a lean version of JavaScript for a cordova application would look like the following (in index.js)…

var app = {
    init: function() {
        document.addEventListener('deviceready', this.main, false);
    },
    main: function() {
        document.getElementById('main').innerText = 'App is ready...'
    }
};

app.init();

Here we are calling the “init” function which will add a listener for the “deviceready” event. When this event fires the “main” function will run, which in this case just changes the inner text of a div element So if we run this using

$ cordova emulate android

or

$ cordova emulate ios

from the root of our project we will see our device boot up, our app launch, and if all goes well we will see the text “App is ready…” so we know that our event is firing.

Read More »

, , , , , , , , , , ,
Share Tweet Reccomend

Introduction to React

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 mentioned earlier that there are a number of different MVW/MV* JavaScript frameworks and all of them have different implementations in how they handle the various aspects of a JavaScript application. Naturally they all have different ways that they handle rendering visual representations of the data that the application is handling. Backbone.js natively uses Underscore.js templates, Ember users Handlebars.js, and Knockout.js and Angular have their own syntax. With a little bit of work you can swap view engines within these frameworks if you so choose. And it would be here where we could incorporate React to handle the view rendering portion of an application. But, as mentioned above, React is not dependent on any JavaScript framework being in place. It can be used as a standalone aspect of an application almost entirely independent from any other library or environment.

So why go to the trouble to incorporate React? Why not just use a framework’s native rendering engine (if you are using a framework). If you are not using a framework, why not just use something like jQuery to handle your view layer? Again, looking at the React homepage, the following description is provided…

React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.

As it turns out there are a number of different positive aspects in terms of performance, scalability, and simplicity that React can provide to application development as it progresses along in both size and complexity. We will explore these in detail as we go forward. As many have noticed, React is a little bit unorthodox from “traditional” JavaScript application development (if there were such a thing) and it can take a little bit of working with it and a little bit of trial and error before many of the benefits of it are fully realized. Indeed, many developers admit that they did not quite “get it” at first and some have even described a substantial initial aversion to some of its implementations. So if you experience this on any level, you are definitely not alone and I would merely invite you to “stick with it” through some of the initial tutorials before you run for the hills screaming in terror. Who knows? You just might be surprised at the end of the day.

Note: For the following discussions want to run our various projects inside of a localhost HTTP web server. If you have a local Apache or IIS setup you may wish to use this by putting the files that you create in the upcoming tutorials in a directory created inside the www folder. Another quick easy implementation is to just pull down the Node.js http-server module by running the following from your command line…

$ npm install -g http-server

From there you can create a directory anywhere you like and run the following…

$ http-server

This will run an HTTP server at localhost:8080. If you got to https://localhost:8080 you should see something there that tells you a server is running.

React is a view rendering JavaScript library that is created and maintained by a team of engineers at Facebook. It is responsible for dynamically handling the visual display of various components within a web site or web application in a flexible, efficient, and interactive manner. What this often means is that React handles the displaying of the data that underlies an application and will dynamically update everything that it needs to in a performance conscious manner when that data changes. We will look at all of React’s various components that come together to make this happen in greater detail as we go along in the upcoming tutorials.

Perhaps the best thing to do is to jump right in and get our first look at React. To start out we will need an index.html file. So create a new file in a directory where you want to run things from and create a file called index.html. In this file place the following code…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>

</body>
</html>

So we are first loading up the React library over CDN and we are also loading up something called the “JSXTransformer.” React has its own programming language called JSX. It is React’s own special easy-to-read abstracted syntax that in the end gets converted to native JavaScript. It is important to note that using JSX is optional. It is not required to create React applications and you can write your React components in native JavaScript if you so choose. For a lot of the upcoming examples provided in what is to follow, we will look at the same code written in both JSX and native JavaScript and you can decide which is more appealing to you. We will discuss the pros and cons of leveraging JSX bit later on as well.

Hello World in React

So now that we have React loaded up, let’s write our first React component. We will do the obligatory “Hello World” example that has so ubiquitous throughout programming tutorials since the dawn of time. We are going to personalize this a bit more though and we are going to say “hello” to an individual rather than the entire world.

JSX

So let’s start by looking at the JSX syntax just to get a look at it. Create a folder called “js” and create a file called hello.jsx and include it after the scripts like so…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>
    <script type="text/jsx" src="js/hello.jsx"></script>
</body>
</html>

In this file add the following JSX code…

var HelloMessage = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

React.render(<HelloMessage name="John" />, document.body);

Now let’s open this index.html in your favorite browser in your web server. You should see the message “Hello John” displayed. Congratulations, you have just written your first React component!

Read More »

, , , , , ,
Share Tweet Reccomend

Creating an MVC Express.js Application (Part 2): Middleware and Configuration

Previously, in an earlier installment we discussed some initial considerations for creating an application in Express.js following the Model View Controller (MVC) design pattern. We’ll pick up where we left off in what follows. The focal point will center around middleware and configuration…

Middleware

One of the things that we are going to want to implement in our application is middleware. There is a pretty good list of Express.js middleware in the Express.js project. Middleware is an important component of Express.js applications. You couple probably think of a middleware function or method as a function that runs on every request/response cycle at whatever point you want to specify. For example, if you wanted to see if the current user who is making the request is authenticated on every single request, you might have this authentication check run in a middleware function before issuing the response. That’s just one example, but there are many other pieces of functionality that you can run within middleware functions.

So let’s add some of the common Express.js middlewares. One useful middleware utility that we can use is a logging component. This will give us information about all of the requests made as our application runs. Express.js uses something called Morgan to accomplish this.

To add middleware, we’re going to want to add it to our package.json file as a dependency. So let’s update our package.json file to look like the following

{
    "name": "MVC-Express-Application",
    "description": "An Express.js application using the MVC design pattern...",
    "version": "0.0.1",
    "dependencies": {
        "express": "4.4.4",	
        "express-handlebars": "1.1.0",
        "morgan": "1.1.1",
    }
}

Don’t forget that we have to install our new module as well. Fortunately, Node.js and npm make this easy. All we have to do is run $ npm install again and all of our packages will be updated…

$ npm install

Now that our dependency is installed, we need to add a reference to it in our main application file…

var logger = require('morgan');

Let’s add the following lines of code to our main app.js file…

/* Morgan - https://github.com/expressjs/morgan
 HTTP request logger middleware for node.js */
app.use(logger({ format: 'dev', immediate: true }));

Now if we run our application and look at our CLI window we can see all the requests being output on every request response cycle. And just like that, we have made use of our first middleware.

Read More »

, , , ,
Share Tweet Reccomend

JavaScript Templates with Handlebars.js

Templates are a very important part of modern day web applications written in JavaScript. Templating essentially encompasses the visual UI (user interface) components of these applications by rendering different “views” depending on the current state of the application. A “view” can be thought of as a certain type of layout. For example, when you sign in to an application and go to your account settings, you might be looking at a “profile” view. Or, if you were using an e-commerce application and you were browsing the site’s inventory, you might be looking at a “products” view. These views are dynamic in nature because they receive data that gets sent to them and then they render that data out in a manner that is meaningful and useful to the user.

There are many different templating libraries that can be used to render views in a JavaScript web application. No one library is necessarily better than another and it is likely that they all have their various strengths and weaknesses. We have looked at a couple of ways to do templates in Backbone.js applications and we’ll revisit one of the libraries used there: Handlebars.js. Handlebars is one of the templating libraries that I like very much for it’s simplicity and intuitive syntax. The Handlebars.js homepage has some very clear straightforward examples that allow you to jump right in to learning how to use it.

Handlebars template setups will look something like the following…

<!DOCTYPE html>
<html>
<head>
<title>Handlebars</title>
<script src="js/jquery.js" type="text/javascript"></script> 
<script src="js/handlebars.js" type="text/javascript"></script> 
</head>
<body>
  
<div class="content"></div>
 
<script id="artist-list-template" type="text/x-handlebars-template">
 
<h1>{{ title }}</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Hometown</th>
      <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
      {{#each artists}}
      <tr>
          <td>{{ name }}</td>
          <td>{{ hometown }}</td>
          <td>{{ favoriteColor }}</td>
      </tr>
      {{/each}}
  </tbody>
</table>
</script>
 
</script>
  
  
<script type="text/javascript">
var data = {
    title: 'Artist Table', 
    artists: [
        { id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' },
        { id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' },
        { id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' }
    ]
}
 
var source = jQuery('#artist-list-template').html();
var template = Handlebars.compile(source);
var html = template(data);
jQuery('.content').html(html);
 
</script>
</body>
</html> 

What we are doing here is passing data (in this case the JSON object in our data into) our artist list template (the one with id: #artist-list-template). Note that with our array or artists inside the {{ #each artists }} block (where we are looping over an array of JSON objects) the context has changed so we can directly refer to the artist name, hometown, and favoriteColor properties in for each item

In this example, we are using a static data object that we have created inline but in a real application it’s likely that you’d be getting that data via AJAX requests to APIs somewhere. But whether you get your data from a server or create it locally, the important part is that data can then be passed into the Handlebars template to be displayed by Handlebars. That is where using a templating engine becomes very efficient and very useful. The view/template does not need to worry about handing anything in the data. All of the code to handle getting data and then searching and sorting through it can be handled elsewhere. All your Handlebars template has to worry about is displaying the “final result” that your code generated elsewhere has produced.

There is also support for doing “multi-level” references of you have a JSON object that is x layers deep, you can refer to the properties inside it by normal dot syntax you might be familiar with.

<div class="entry">
  <h1>{{title}}</h1>
  <h2>By {{author.name}}</h2>

  <div class="body">
    {{body}}
  </div>
</div>

<script type="text/javascript">
var data = {
  title: "A Blog Post!",
  author: {
    id: 42,
    name: "Joe Smith"
  },
  body: "This is the text of the blog post"
};
</script>

And there is even the possibility of doing conditionals via the built-in helper methods. For example, here is an if conditional in a Handlebars template where if a property does not exist or is null in an object that is passed to the view, a different “block” of code will be rendered.

<div class="entry">
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>

And this is just scratching the surface. There are many other features and functionality that Handlebars.js provides. So head on over to the Handlebars.js homepage to start taking a look through the examples there to see what can be accomplished.

As we have seen Handlebars.js is very useful for creating a view layer in single-page JavaScript applications. Ember.js applications Handlebars.js by default, but you could certainly integrate Handlebars into applications built with other libraries. One of these examples is discussed here. But it should also be noted that there is also support for using Handlebars to render HTML on the server in a Node.js application before it is sent to the browser. For example, if you were building an Express.js application, you could use the express-handlebars module to handle the view component of your appplication by creating some dynamically generated HTML to server up to the browser. For more info on Node.js see this entry here, and for more info on building Express.js applications on top of Node.js see this entry here.

Hopefully you have found this discussion of Handlebars.js useful and that you consider using it for your templating needs in your next application. Download the files below to play around with this useful library…

Download Files
, , ,
Share Tweet Reccomend

Using Templates in Backbone.js

One of the more important components of Backbone.js is using templates. What are templates? Templates are essentially pieces of markup that you can use to create a bunch of different reusable copies of that markup (including all the styles and hierarchy that you want) but populating each component with different data. Used in combination with views, they are great for doing such as iterating over a collection of models to display a list of data for some purpose. You’ll see how it all fits together in what follows.

By default, Backbone.js uses the templating engine of Underscore.js which makes sense because Backbone has a hard dependency on Underscore. However, if you’re not a big fan of the way that Underscore does templating or you just want to use another templating engine, Backbone allows for that as well. The possibilities are limitless. But let’s first take a look at an Underscore.js template because that will work out of the box with Backbone.js. You do not need to load up anything else to use templates.

Read More »

, , ,