How to build an application using a single page architecture and HTML templates.

How to build (compile and package) an application for 6 platforms using PhoneGap Build.

To complete this tutorial, all you need is a code editor, a modern browser, and a connection to the Internet. A working knowledge of HTML and JavaScript is assumed, but you don’t need to be a JavaScript guru.

Part 1: Choosing a Local Storage Option

Step 1: Explore different persistence mechansisms

Open the following files in phonegap-workshop-master/js/storage, and explore the different persistence stores they define:

memory-store.js (MemoryStore)

ls-store.js (LocalStorageStore)

websql-store.js (WebSqlStore)

Step 2: Test the application with different persistence mechanisms

To change the local persistence mechanism for the application:

In index.html: add a script tag for the corresponding .js file: memory-store.js, ls-store.js, or websql-store.js.

In js/main.js: Instantiate the specific store in the initialize() function of the app object: MemoryStore, LocalStorageStore, or WebSqlStore.

To test the application, open index.html in your browser, or simply double-click index.html on your file system. Type a few characters in the search box to search employees by name. Clicking an employee link doesn’t produce any result at this time.

Part 2: Building with PhoneGap Build

Click the “new app” button to create a new application on PhoneGap Build.

Either point to a GitHub repository where you push your code for this workshop, or zip up your phonegap-workshop directory and upload it to PhoneGap Build.

Click the Ready to build button.

The iOS button will immediately turn red because the iOS build requires that you upload your Apple Developer certificate and an application provisioning profile. You can find more information here if you haven’t already signed up for the Apple Developer Program. If you don’t have an iOS device, or if you are not ready to upload your developer certificate, you can skip step 5 and keep running the application in the browser or a non iOS device.

If you used the GitHub approach, sync with GitHub and click the Update Code button in PhoneGap Build.
If you used the zip file approach, zip up your phonegap-workshop directory and upload the new version to PhoneGap Build

There are many other parameters you can specify in config.xml to configure the build process. See the documentation for config.xmlhere.

Part 3: Using Native Notification

A default webview alert gives away the fact that your application is not native. In this section, we set up the basic infrastructure to display native alerts when the application is running on a device, and fall back to default browser alerts when running in the browser.

In index.html, add the following script tag (as the first script tag at the bottom of the body):

1

<scriptsrc="phonegap.js"></script>

This instructs PhoneGap Build to inject a platform specific version of phonegap.js at build time. In other words, phonegaps.js doesn’t need to be (and shouldn’t be) present in your project folder.

In main.js, define a function named showAlert() inside the app object. If navigator.notification is available, use its alert() function. Otherwise, use the default browser alert() function.

1

2

3

4

5

6

7

showAlert: function(message, title) {

if(navigator.notification) {

navigator.notification.alert(message, null, title, 'OK');

} else{

alert(title ? (title + ": "+ message) : message);

}

},

Test the notification logic by displaying a message when the application store has been initialized: Pass an anonymous callback function as an argument to the constructor of the persistence store (the store will call this function after it has successfully initialized). In the anonymous function, invoke the showAlert() function.

1

2

3

4

5

6

7

initialize: function() {

varself = this;

this.store = newMemoryStore(function() {

self.showAlert('Store Initialized', 'Info');

});

$('.search-key').on('keyup', $.proxy(this.findByName, this));

}

Test the application: When you run the application in the browser, you should see a standard browser alert. When you run the application on your device, you should see a native alert.

Part 4: Setting Up a Single Page Application

A single page application is a web application that lives within a single HTML page. The “views” of the application are injected into- and removed from the DOM as needed as the user navigates through the app. A single page application architecture is particularly well suited for mobile apps:

The absence of continual page refreshes provides a more fluid / closer to native experience.

The UI is entirely created at the client-side with no dependency on a server to create the UI, making it an ideal architecture for applications that work offline.

In this section, we set up the basic infrastructure to turn Employee Directory into a single page application.

In index.html: remove the HTML markup inside the body tag (with the exception of the script tags).

In main.js, define a function named renderHomeView() inside the app object. Implement the function to programmatically add the Home View markup to the body element.

1

2

3

4

5

6

7

8

9

10

renderHomeView: function() {

varhtml =

"<div class='header'><h1>Home</h1></div>"+

"<div class='search-view'>"+

"<input class='search-key'/>"+

"<ul class='employee-list'></ul>"+

"</div>"

$('body').html(html);

$('.search-key').on('keyup', $.proxy(this.findByName, this));

},

Modify the initialize() function of the app object. In the anonymous callback function of the store constructor, call the renderHomeView() function to programmatically display the Home View.

1

2

3

4

5

6

initialize: function() {

varself = this;

this.store = newMemoryStore(function() {

self.renderHomeView();

});

}

Part 5: Using Handlebar Templates

Writing HTML fragments in JavaScript and programmatically inserting them into the DOM is tedious. It makes your application harder to write and harder to maintain. HTML templates address this issue by decoupling the UI definition (HTML markup) from your code. There are a number of great HTML template solutions: Mustache.js, Handlebar.js, and Underscore.js to name a few.

In this section, we create two templates to streamline the code of the Employee Directory application. We use Handlebar.js but the smae result can be achieved using the other HTML template solutions.

Modify index.html as follows:

Add a script tag to include the handlebar.js library:

1

<scriptsrc="lib/handlebars.js"></script>

Create an HTML template to render the Home View. Add this script tag as the first child of the body tag:

1

2

3

4

5

<scriptid="home-tpl"type="text/x-handlebars-template">

<divclass='header'><h1>Home</h1></div>

<divclass='search-bar'><inputclass='search-key'type="text"/></div>

<ulclass='employee-list'></ul>

</script>

Create an HTML template to render the employee list items. Add this script tag immediately after the previous one:

Modify renderHomeView() to use the homeTpl template instead of the inline HTML:

1

2

3

4

renderHomeView: function() {

$('body').html(this.homeTpl());

$('.search-key').on('keyup', $.proxy(this.findByName, this));

},

Modify findByName() to use the employeeLiTpl template instead of the inline HTML:

1

2

3

4

5

6

findByName: function() {

varself = this;

this.store.findByName($('.search-key').val(), function(employees) {

$('.employee-list').html(self.employeeLiTpl(employees));

});

},

Test the application.

Part 6: Creating a View Class

It’s time to provide our application with some structure. If we keep adding all the core functions of the application to the app object, it will very quickly grow out of control. In this section we create a HomeView object that encapsulates the logic to create and render the Home view.

Step 1: Create the HomeView Class

Create a file called HomeView.js in the js directory, and define a HomeView class implemented as follows:

Define an initialize() function inside the HomeView class. Define a div wrapper for the view. The div wrapper is used to attach the view-related events. Invoke the initialize() function inside the HomeView constructor function.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

varHomeView = function(store) {

this.initialize = function() {

// Define a div wrapper for the view. The div wrapper is used to attach events.

Move the renderHomeView() function from the app object to the HomeView class. To keep the view reusable, attach the html to the div wrapper (this.el) instead of the document body. Because the function is now encapsulated in the HomeView class, you can also rename it from renderHomeView() to just render().

1

2

3

4

this.render = function() {

this.el.html(HomeView.template());

returnthis;

};

Move the findByName() function from the app object to the HomeView class.

1

2

3

4

5

this.findByName = function() {

store.findByName($('.search-key').val(), function(employees) {

$('.employee-list').html(HomeView.liTemplate(employees));

});

};

Step 2: Using the HomeView class

In index.html, add a script tag to include HomeView.js (just before the script tag for main.js):

1

<scriptsrc="js/HomeView.js"></script>

Remove the renderHomeView() function from the app object.

Remove the findByName() function from the app object.

Modify the initialize function() to display the Home View using the HomeView class:

In index.html, modify the home-tpl template: change the search-key input type from text to search.

Test the application. Specifically, test the list behavior when the list is bigger than the browser window (or the screen)

Step 2: Native Scrolling Approach

Modify the home-tpl template in index.html. Add a div wrapper with a scroll class around the ul element with a scroll:

1

2

3

4

5

<scriptid="home-tpl"type="text/x-handlebars-template">

<divclass='header'><h1>Home</h1></div>

<divclass='search-bar'><inputclass='search-key'type="search"/></div>

<divclass="scroll"><ulclass='employee-list'></ul></div>

</script>

Add the following class definition to css/styles.css:

1

2

3

4

5

6

7

8

9

.scroll{

overflow: auto;

-webkit-overflow-scrolling: touch;

position: absolute;

top: 84px;

bottom: 0px;

left: 0px;

right: 0px;

}

If the platforms you target support touch-based scrolling of fixed regions, this approach is all you need (you can skip step 3 below). If not, you’ll need to implement a programmatic approach, typically with the help of a library such as iScroll.

Step 3: iScroll Approach

Add a script tag to include the iscroll.js library:

1

<scriptsrc="lib/iscroll.js"></script>

In HomeView.js, modify the findByName() function: Instantiate an iScroll object to scroll the list of employees returned. If the iScroll object already exists (), simply refresh it to adapt it to the new size of the list.

Part 8: Highlighting Tapped or Clicked UI Elements

In styles.css, add a tappable-active class definition for tapped or clicked list item links. The class simply highlights the item with a blue background:

1

2

3

4

li>a.tappable-active {

color: #fff;

background-color: #4286f5;

}

In main.js, define a registerEvents() function inside the app object. Add a the tappable_active class to the selected (tapped or clicked) list item:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

registerEvents: function() {

varself = this;

// Check of browser supports touch events...

if(document.documentElement.hasOwnProperty('ontouchstart')) {

// ... if yes: register touch event listener to change the "selected" state of the item

$('body').on('touchstart', 'a', function(event) {

$(event.target).addClass('tappable-active');

});

$('body').on('touchend', 'a', function(event) {

$(event.target).removeClass('tappable-active');

});

} else{

// ... if not: register mouse events instead

$('body').on('mousedown', 'a', function(event) {

$(event.target).addClass('tappable-active');

});

$('body').on('mouseup', 'a', function(event) {

$(event.target).removeClass('tappable-active');

});

}

},

Invoke the registerEvents() function from within the app object’s initialize() function.

Test the application.

Part 9: View Routing

In this section, we add an employee details view. Since the application now has more than one view, we also add a simple view routing mechanism that uses the hash tag to determine whether to display the home view or the details view for a specific employee.

Step 1: Create the employee template

Open index.html and add a template to render a detailed employee view:

Define an initialize() function inside the HomeView class. Define a div wrapper for the view. The div wrapper is used to attach the view related events. Invoke the initialize() function inside the HomeView constructor function.

Step 3: Implement View Routing

In the app’s registerEvents() function, add an event listener to listen to URL hash tag changes:

1

$(window).on('hashchange', $.proxy(this.route, this));

In the app object, define a route() function to route requests to the appropriate view:

If there is no hash tag in the URL: display the HomeView

If there is a has tag matching the pattern for an employee details URL: display an EmployeeView for the specified employee.

1

2

3

4

5

6

7

8

9

10

11

12

13

route: function() {

varhash = window.location.hash;

if(!hash) {

$('body').html(newHomeView(this.store).render().el);

return;

}

varmatch = hash.match(app.detailsURL);

if(match) {

this.store.findById(Number(match[1]), function(employee) {

$('body').html(newEmployeeView(employee).render().el);

});

}

}

Modify the initialize() function to call the route() function:

1

2

3

4

5

6

7

8

initialize: function() {

varself = this;

this.detailsURL = /^#employees\/(\d{1,})/;

this.registerEvents();

this.store = newMemoryStore(function() {

self.route();

});

}

Test the application.

Part 10: Using the Location API

In this section, we add the ability to tag an employee with his/her location information. In this sample application, we display the raw information (longitude/latitude) in the employee view. In a real-life application, we would typically save the location in the database as part of the employee information and show it on a map.

The code below works when running the application as a PhoneGap app on your device. It should also work in Chrome on the desktop when the page is served with the http:// protocol, and in Firefox, regardless of the protocol (http:// or file://).

In index.html, add the following list item to the employee-tpl template:

1

<li><ahref="#"class="add-location-btn">Add Location</a></li>

In the initialize() function of EmployeeView, register an event listener for the click event of the Add Location list item:

Part 12: Using the Camera API

In this section, we use the PhoneGap Camera API to provide the user with the ability to take a picture of an employee, and use that picture as the employee’s picture in the application. We do not persist that picture in this sample application.

The code below only works when running the application on your device as a PhoneGap app. In other words, you can’t test it in a browser on the desktop.

In index.html, add the following list item to the employee template:

1

<li><ahref="#"class="change-pic-btn">Change Picture</a></li>

In the initialize() function of EmployeeView, register an event listener for the click event of the Change Picture list item: