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

Create Mobile Applications for iOS and Android with HTML5, JavaScript, and Apache Cordova

Obviously at the time of this writing in the 2nd decade of the 21st century, you are no doubt well acquainted with the immense proliferation and impact that mobile apps have had in and on our world. It was not long ago that we were all sitting at our computers at our desks for the large majority of the time we spent in our various avenues of technological communications over the Internet — complete with our with our giant monitors, whirring computer fans, buzzing drives, and the garbled noise of dial-up modems. Now, mobile phones and tablets probably make up as much, if not more, of our time spent working, playing, and communicating online. Everyone has a ~$100 to $600 smartphone (i.e. computer) in their pocket. And with this rise of mobile, apps found on the popular stores — like Apple’s iOS App Store, Google Play (Android), Amazon and a host of others — have completely transformed the way that we do anything and everything because well, there is an app for anything and everything. Every single facet of life probably has an app to manage some aspect of it. Need to remember to breathe? There is an app for that! Yeah, that is a joke (probably)… but there are plenty of “real” apps out there (e.g. iBeer) that are just as pointless. Fun and goofy, yes, but pointless. And they all post their pointlessness to Facebook and/or Twitter.

Whether you want to develop an app to manage some minute aspect of life or just create a fun game, or whatever else, you can download the SDK for the platform(s) that you want to release your app on, do some tutorials, and start building. That’s all well and good, but if you want to port your application to another platform (e.g. release an iOS app also for Android), you will essentially have to try rebuild the same app using the languages in tools of a different platform. For example, iOS apps for iPhone and iPad have traditionally been developed on a Mac in the Xcode IDE using the Objective-C programming language (though Apple has recently released a new language called Swift that can also be used to build iOS apps). Android apps, by contrast are built using Java and Eclipse or the more recently released Android Studio. Native Windows Phone apps are built using C# and XAML in Visual Studio. Other platforms have their own setups. If you want to take this approach you definitely can, but it should be fairly apparent that developing and maintaining a number of different codebases for multiple platforms quickly adds up to a lot of time, effort, and often money as the sizes and complexity of your apps increase.

At the same time as the rise of mobile in the past decade, something else has occurred: the rise of HTML5 and JavaScript web applications. Beginning at around 2009 – 2010 one of the more noticeable developments was the rise of websites and web applications making use of more open technologies such as HTML5 and JavaScript to bring interactivity and 2-way communication between clients (usually browsers) and servers. With Flash on the way out due its proprietary nature, resource hogging, security issues, poor SEO — along with its being snubbed by Apple for support on iPhones and iPads for basically all these reasons — meant that something had to fill the void. HTML5 and JavaScript moved into this space and developers started turning to it for creating interactive “app-like” experiences.

Wouldn’t it be awesome if there were a way to write a single application in HTML and JavaScript with a single codebase and have a way to port this application to all of the different mobile platforms? I am so glad you asked.

Apache Cordova — also commonly known as “PhoneGap” (the only difference between the two is propriety) — allows us combine combine these open technologies together with the SDKs of the various mobile application platforms to make native mobile applications using technologies such as HTML and JavaScript. You can basically create a small static HTML and JavaScript website or web application and this code will be imported into native iOS, Android, Windows Phone projects and configured specifically for the respective platforms. Thus, you *do* still have to have the SDK of the platform installed to build, run, and release the apps. So to create an iOS app you will still need a Mac and Xcode. To create Android apps you will need to install the Android SDK (which comes with the Android Studio IDE). If you don’t want to mess around with Android Studio, you can just try downloading the old standalone SDK tools here and updating from there. But the important aspect of using Cordova is that the HTML and JavaScript that each project will pull in and build will be the same across all platforms. Want to release an update with some slick new features or fix some bugs that have been reported by your users? You need only change your code in your HTML and JavaScript. You don’t have to try and rewrite the same code and/or functionality in a different language on each platform. From there all you need to do is run a few simple commands from the command lines and your HTML and JavaScript will get built and converted into an application that can run on the platform(s) you are targeting.

In what follows we will explore what it looks like to use Cordova to create a mobile application in HTML and JavaScript that can run on a number of different platform. For our examples, we will build our app for iOS and Android, but the process is essentially the same for building for other platforms (e.g. Microsoft Windows Phone, Amazon Kindle Fire). You would just need to download the SDKs for those platforms if you wanted to run your app on those types of devices as well.

Read More »

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

An Angular 2 Primer

Angular 2 is the much anticipated latest release of the Angular platform maintained by a team of engineers over at Google. The first iteration of Angular (which we may refer to as Angular 1 or 1.X at times) was and has been very well received within the JavaScript community. Many saw it as an improvement on smaller single-page application libraries like Backbone.js and Knockout.js because it essentially did “more” for you. You got a lot of functionality out of the box with the result being that you had to write less boilerplate code than you would with using a more basic library. Directives allow you to define custom attributes for any element that you want and Angular also boasts other great features such as native data-binding, an AMD like module loading system, and services using a solid promise implementation for asynchronous data transfer. All of this and more comes pre-packaged within Angular and is coupled with a great community behind it, an abundance of resources, as well as great support from the team over at Google. Because of all this, it is not too surprising that many companies and organizations have turned to it as a solution for building their web and mobile applications.

If there were a few points of criticism of Angular as a framework, it usually surrounded a slightly steeper learning curve when compared to other libraries, and the observation that perhaps there was a little “too much magic” going on under the hood without the developer really fully understanding what is happening 100% in all circumstances. This is always a double-edged sword with a framework that gives you a lot of functionality out of the box. On one hand, it is great to have a system where writing a relatively small amount of code will give you a lot of dynamic features and functionality with minimal effort. On the other hand, this sometimes requires that you follow a very defined and specific pattern in the way that you structure your code and if you ever want to do something that is perhaps a bit unorthodox from the accepted way, it might not be so easy and a framework that is a bit more rigid when it comes to custom implementations not always desired — especially when those hard-to-track-down bugs surface at inopportune times. Like with so many things, there will always be pros and cons to any technology you encounter.

Nonetheless, the reception and response to Angular 1 was/is overall very positive. It was often paired with Node.js development using the web application framework Express.js and the NoSQL database MongoDB to create what was known as the MEAN stack (MongoDB, Express, Angular, Node.js). Many readers may be familiar with this and other technology paring acronyms (such as LAMP: Linux, Apache, MySQL, and PHP or Python). When certain groupings of technologies complement each other well and play together nicely, it always makes for a better development experience all around.

Angular 2 Announcement and Pushback

In the latter part of 2014 Google announced that they were developing Angular 2. Usually these sorts of announcements are met with are met with a lot of excitement. After all, who wouldn’t like a shiny new version of something that you already like. However there was one overarching dark cloud the loomed over the Angular 2 announcement that was met with a lot of frustration within the web development community: Angular 2 would be essentially a rewrite of the codebase and drastically different enough from Angular 1.X such that there would be no foreseeable upgrade path to move from Angular 1.X to Angular 2. This meant that existing applications in Angular 1.X would essentially have to be rewritten. On top of this, it was not immediately clear how long Angular 1.X would continue to be supported with new releases and bug fixes.

Naturally, of course, some developers were upset by this. Only time will tell what the full impact of this decision and approach will be. Nonetheless, we move forward towards the future regardless of how much of the past comes along with it. That’s what we are aiming to do in the following discussions and tutorials.

NOTE: At the time of this writing it is still not entirely clear whether any of this will change and the Angular team will put an upgrade path in place. Also note, at the time of this writing in mid-2015, Angular 2 is still in “developer preview.” This means that many of the concepts and code samples presented in this book are subject to change. I will do my best to keep up to date on the latest changes as they roll out, but please note that there might be some sensitivity involved with functionality between different versions of Angular 2 and its surrounding tools. If you encounter anything in this regard, please do not hesitate to contact me via the above channels.

Introduction to Angular 2

Angular 2 incorporates many modern features of the latest iterations of JavaScript and tools within the JavaScript community being released circa halfway through the second decade of the 21st century (2010 – 2020). This includes many syntactical and functional features of ECMAScript 6 — the latest iteration of JavaScript up from ECMAScript 5, Node.js based dependency management with npm , TypeScript — the type checking JavaScript utility syntax that has been built and maintained by Microsoft, and a number of others. In short, the fingerprints of many of the newest emerging technologies within the web development world during this window of time are present on the Angular 2 framework. Similar to those that have come before, each release of Angular 2 will attempt to be a more malleable and useful option for developers looking to solve the common problems that they all face.

So let’s look all of these pieces that are essential for developing an Angular 2 application…

Node.js

Angular 2 uses Node.js and more specifically npm for installation of the various dependencies it requires. Having been first published by Ryan Dahl in 2009, Node.js — the open source software that allows the common web language of JavaScript to run outside the browser — has absolutely grabbed ahold of imaginations in the world of technology in its first half-decade of life. The explosion of Node.js applications and the exponentially increasing number of published modules of npm, the repository where Node.js modules are stored, are a huge indicator of its success as a platform.

So be sure head over to the Node.js website and install it for your OS. You will definitely be needing it as we go along.

ECMAScript 6

Angular 2 uses many implementations found in ECMAScript 6, or ES6 for short. It would be beneficial to take a brief look at some of the new features found in this latest version of JavaScript up from ES5. For example, ECMAScript 6 implements a more syntactical conceptualization of classes in JavaScript. While JavaScript classes are not and never have been classes in the strictest technical sense as they are in the traditional object-oriented languages Java, C++, and C#, many JavaScript applications can still be written in a way that incorporates a very class-like implementation using functions, constructors and prototypal inheritance. For example, you will often see something the following in a JavaScript application (ES5):

// ES5
function Animal() {
    this.color = 'brown';
    this.size = 'medium';
    this.age = 1;
}
Animal.prototype.sound = function() {
    console.log('Grunt');
};
Animal.prototype.move = function() {
    console.log('Running');
};

var beast = new Animal();

Inheritance can even be implemented in this approach…

function Dog() {
    Animal.call(this);
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog

var fido = new Dog();
fido.color // brown;

By calling the Animal function and passing in the Dog function as the context, and new instance of a Dog will get all of the properties and methods found on Animal. We then do a little bit of additional cleanup with some of the prototype to make sure that the pointers are pointing at the right place.

Read More »

, , ,
Share Tweet Reccomend

JavaScript Routing

One of the more important pieces of any client-side JavaScript framework is the routing of requests when users navigate to different places. Basically a JavaScript router in a client-side application will listen for changes in the hash location and update the data and UI in the page accordingly, making all of the API calls that it needs to do so. But how is this feat accomplished? How do we match a route pattern defined in a JavaScript framework to an actual route navigated to by the user? This is something we will look at in what follows.

Normally, when you talk about matching you immediately think to look at regular expressions. However, the way that routes are defined in client side applications often have patterns that are a little bit different that the actual routes that will be navigated to by users. What do we mean by this? We talked about routing in Backbone.js here. Basically a Backbone.js router is set up like the following…

var Router = Backbone.Router.extend({
  routes: {
    "": "home", // url:event that fires
    "new": "createNew"
    "edit/:id": "editItem",
    "download/*anything": "downloadItem"
  },
 
  home: function() {
      alert('We have loaded the home view');
  },
 
  createNew: function() {
     alert('We are going to create something new');
  }
 
  editItem: function(idParam) {
      alert('We are going to edit entry number ' + idParam);
  }
 
});
var router = new Router;

In this setup, when a user navigates to a particular route, the function defined in the routes object will run. So if a user were to navigate to the route #/edit/4, the editItem function will run passing in the id 4.

Read More »

, ,