Packaging a jQuery Mobile Application with Cordova/Phonegap
Join the DZone community and get the full member experience.
Join For Freein this article we are going to learn the process of packaging a jquery mobile application with cordova / phonegap. the application that we will use in the article is the meeting room manager app that we’ve been building over the past months.
while we haven’t finished developing the meeting room manager app (only the user registration features are completed at this point), i want to show you how to convert it from a mobile web app to a native hybrid app that you can deploy to a device.
in this article we will focus on deploying to an android device. we will perform an ios deployment in a follow-up article.
a short introduction to cordova
apache cordova is an open-source mobile development framework where you use html, css and javascript to create mobile applications targeting multiple mobile operating systems.
the web applications that you build with cordova run inside native applications called wrappers, that are targeted to each mobile platform. cordova uses standard-compliant api bindings to expose different features of the mobile devices – for example, sensors, data and network status – to your application.
the main benefit of using cordova is that it allows you to use javascript, html and css to develop mobile applications that can run on multiple platforms, bypassing the respective programming languages of each platform.
however, you trade this ease of development for a degraded user experience. the reason is that you are ultimately running a web application on a mobile browser, and mobile browsers have performance and other limitations in their integration with the native features of the device.
setting up the cordova development environment
i developed this particular example on a windows pc. i used cordova version 4.0.0. i performed the following steps to get ready to develop with cordova,:
- install the java sdk
- install ant ( winant )
- install the android sdk
- install node.js
- install a git client
- install the cordova’s command line interface (cli)
if you haven’t set up your cordova development environment yet, you should follow the detailed installation instructions found in the command-line interface section of the cordova documentation.
creating a cordova project
let’s move on to the more interesting parts of the tutorial. we are going to get started by creating a cordova project.
the project’s directory where we created our meeting room manager jquery mobile web application currently looks like this:
we are going to navigate to the project’s directory, open a command window and type the command that creates a cordova project:
> cordova create cordova-project com.miamicoder.bookit bookit
the command will create the cordova-project directory within the project’s directory:
in the cordova-project directory we will find a boilerplate web-based application with a www subdirectory that contains the application’s home page, located in the index.html file.
the www subdirectory itself contains the css, js, img and other subdirectories that hold various project assets. these resources will be stored on the device’s local file system when the application is packaged and deployed.
the config.xml file contains the project metadata that cordova uses to generate and distribute the application. let’s open the file and edit the description and author nodes:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.miamicoder.bookit" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>bookit</name>
<description>
a meeting rooms manager app.
</description>
<author email="miamicoder@gmail.com" href="http://miamicoder.com">
jorge ramon - miamicoder.com
</author>
<content src="index.html" />
<access origin="*" />
</widget>
adding target platforms to a cordova project
we need to specify one or more target platforms to build a cordova project. in this article we are targeting just the android platform. to add it to the project, we need to open a command window in the cordova-project directory and type the following command:
c:\cordova-project>cordova platform add android
be mindful that your computer must support and have installed the target platform’s sdk. we should not have a problem with this requirement because we installed the android sdk earlier.
you can check the installed platform(s) by running the following command:
c:\cordova-project>cordova platforms ls
running the boilerplate cordova application
the following command builds the skeletal cordova application that we just created:
a successfuld build will generate a message similar to the screenshot below:
we can run the boilerplate app on an emulator or a device. we will use the genymotion emulator in this tutorial prior to testing on an actual device.
i highly recommend genymotion to speed up the testing phase of your applications. this emulator provides an experience that’s very close to a physical device. it’s also very fast to load, as opposed to the emulators that come with the android sdk.
installing and setting up genymotion is a breeze. assuming that you’ve already set up genymotion, you can perform the following steps to test the skeletal cordova application:
-
start one of the virtual devices that you defined in genymotion.
- once the genymotion virtual device is running, use the following cordova command to view the application in the virtual device:
cordova run android
-
the command will build the app and deploy it to the connected device, which in this case is genymotion’s. on the device, the app should look like this:
migrating a jquery mobile app to a cordova project
at this point we have our starter cordova project set up and we can focus on migrating our jquery mobile application into it. the migration will consist of these steps:
- move the jquery mobile pages that today exist in their own separate html files over to the index.html file in the cordova project.
- migrate the javascript files located under the project’s js directory over to the cordova-project/www/js directory.
- move the css files located the project’s css files from the css directory to the cordova-project/www/css directory.
adding the jquery mobile references
we will start the jquery mobile pages migration by opening the cordova-project/www/index.html file and adding the references to the jquery mobile library’s css file, as well as our and our app’s css file, in the head section of the html page:
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- warning: for ios 7, remove the width=device-width and height=device-height attributes. see https://issues.apache.org/jira/browse/cb-4323 -->
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=device-dpi" />
<link href="css/themes/2/bookit.min.css" rel="stylesheet" />
<link href="css/themes/2/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="lib/jqm/1.4.5/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="css/app.css" />
<title>bookit</title>
</head>
note how the references are assuming that the library’s files are in the cordova-project/www/css and cordova-project/www/lib directories. we will add these files in a few minutes.
we also need to add the javascript references. add the following entries between the reference to the cordova.js file and the tag, replacing the entry for the js/index.js file:
<script type="text/javascript" src="cordova.js"></script>
<script src="lib/fastclick/fastclick.min.js"></script>
<script src="lib/jquery/2.1.1/jquery-2.1.1.min.js"></script>
<script src="js/api-messages.js"></script>
<script src="js/settings.js"></script>
<script src="js/signup-controller.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="lib/jqm/1.4.5/jquery.mobile-1.4.5.min.js"></script>
fastclick is a library that eliminates the 300ms delay between a physical tap and the firing of a click event on mobile browsers. we will add its files to the cordova project later in the tutorial.
the api-messages.js, settings.js, signup-controller.js and index.js contain our application’s javascript code. we will bring them in from the project’s js directory.
adding the home page
next, we are going to open the index.html file in the project’s root and copy the jquery mobile page’s html code, which is this:
<div data-role="page" id="page-index">
<div data-role="header" data-theme="c" data-position="fixed">
<h1>bookit</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h2 class="mc-text-center">welcome!</h2>
<p class="mc-top-margin-1-5"><b>existing users</b></p>
<a href="#page-signin" class="ui-btn ui-btn-b ui-corner-all">sign in</a>
<p class="mc-top-margin-1-5"><b>don't have an account?</b></p>
<a href="#page-signup" class="ui-btn ui-btn-b ui-corner-all">sign up</a>
<p></p>
</div><!-- /content -->
</div><!-- /page -->
then, we need to open the cordova-project/www/index.html file and replace the div element in the document’s body with the html above. after you paste the code, modify the value of the page’s id attribute so it becomes page-index. also, add the data-position and data-tap-toggle attributes to the page’s header as shown below:
<div data-role="page" id="page-index">
<div data-role="header" data-theme="c" data-position="fixed">
<h1>bookit</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h2 class="mc-text-center">welcome!</h2>
<p class="mc-top-margin-1-5"><b>existing users</b></p>
<a href="#page-signin" class="ui-btn ui-btn-b ui-corner-all">sign in</a>
<p class="mc-top-margin-1-5"><b>don't have an account?</b></p>
<a href="#page-signup" class="ui-btn ui-btn-b ui-corner-all">sign up</a>
<p></p>
</div><!-- /content -->
</div><!-- /page -->
setting the data-position attribute to fixed makes the header float above the content.
adding the sign in page
we are going to follow the same procedure with the sign in page. open the sign-in.html file in the project’s root directory and copy the html code for the sign in page:
<div data-role="page" data-bookit-page="signin">
<div data-role="header" data-theme="c">
<h1>book it</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>sign in</h3>
<label for="txt-email">email address</label>
<input type="text" name="txt-email" id="txt-email" value="">
<label for="txt-password">password</label>
<input type="password" name="txt-password" id="txt-password" value="">
<fieldset data-role="controlgroup">
<input type="checkbox" name="chck-rememberme" id="chck-rememberme" >
<label for="chck-rememberme">remember me</label>
</fieldset>
<a href="#dlg-invalid-credentials" data-rel="popup" data-transition="pop" data-position-to="window" id="btn-submit" class="ui-btn ui-btn-b ui-corner-all mc-top-margin-1-5">submit</a>
<p class="mc-top-margin-1-5"><a href="begin-password-reset.html">can't access your account?</a></p>
<div data-role="popup" id="dlg-invalid-credentials" data-dismissible="false" style="max-width:400px;">
<div role="main" class="ui-content">
<h3 class="mc-text-danger">login failed</h3>
<p>did you enter the right credentials?</p>
<div class="mc-text-center"><a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-b mc-top-margin-1-5">ok</a></div>
</div>
</div>
</div><!-- /content -->
</div><!-- /page -->
then, go to the cordova-project/www/index.html file and paste the code immediately below the index page. make sure to modify the page’s id attribute and the header div as shown below:
<div data-role="page" id="page-signin">
<div data-role="header" data-theme="c" data-position="fixed">
<a href="#page-index" data-icon="home" data-iconpos="notext" data-transition="slide" data-direction="reverse"></a>
<h1>bookit</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>sign in</h3>
<label for="txt-email">email address</label>
<input type="text" name="txt-email" id="txt-email" value="">
<label for="txt-password">password</label>
<input type="password" name="txt-password" id="txt-password" value="">
<fieldset data-role="controlgroup">
<input type="checkbox" name="chck-rememberme" id="chck-rememberme">
<label for="chck-rememberme">remember me</label>
</fieldset>
<a href="#dlg-invalid-credentials" data-rel="popup" data-transition="pop" data-position-to="window" id="btn-submit" class="ui-btn ui-btn-b ui-corner-all mc-top-margin-1-5">submit</a>
<p class="mc-top-margin-1-5"><a href="begin-password-reset.html">can't access your account?</a></p>
<div data-role="popup" id="dlg-invalid-credentials" data-dismissible="false" style="max-width:400px;">
<div role="main" class="ui-content">
<h3 class="mc-text-danger">login failed</h3>
<p>did you enter the right credentials?</p>
<div class="mc-text-center"><a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-b mc-top-margin-1-5">ok</a></div>
</div>
</div>
</div><!-- /content -->
</div><!-- /page -->
notice how we added a back button to the header:
<div data-role="header" data-theme="c" data-position="fixed" data-tap-toggle="false">
<a href="#page-index" data-icon="home" data-iconpos="notext" data-transition="slide" data-direction="reverse"></a>
<h1>bookit</h1>
</div><!-- /header -->
the button will allow users to navigate back to the index page if they choose to. we used the data-iconpos attribute to define that we want an icon-only button:
the data-transition and data-direction attributes allow us to define a reverse slide transition for the navigation back to the index page.
adding the sign up page
now, on to the sign up page. open the sign-up.html file in the project’s root directory and copy the page’s html code:
<div data-role="page" id="page-signup">
<div data-role="header" data-theme="c">
<h1>bookit</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>sign up</h3>
<div id="ctn-err" class="bi-invisible"></div>
<label for="txt-first-name">first name</label>
<input type="text" name="txt-first-name" id="txt-first-name" value="">
<label for="txt-last-name">last name</label>
<input type="text" name="txt-last-name" id="txt-last-name" value="">
<label for="txt-email-address">email address</label>
<input type="text" name="txt-email-address" id="txt-email-address" value="">
<label for="txt-password">password</label>
<input type="password" name="txt-password" id="txt-password" value="">
<label for="txt-password-confirm">confirm password</label>
<input type="password" name="txt-password-confirm" id="txt-password-confirm" value="">
<!--<a href="#dlg-sign-up-sent" data-rel="popup" data-transition="pop" data-position-to="window" id="btn-submit" class="ui-btn ui-btn-b ui-corner-all mc-top-margin-1-5">submit</a>-->
<button id="btn-submit" class="ui-btn ui-btn-b ui-corner-all mc-top-margin-1-5">submit</button>
<div data-role="popup" id="dlg-sign-up-sent" data-dismissible="false" style="max-width:400px;">
<div data-role="header">
<h1>almost done...</h1>
</div>
<div role="main" class="ui-content">
<h3>confirm your email address</h3>
<p>we sent you an email with instructions on how to confirm your email address. please check your inbox and follow the instructions in the email.</p>
<div class="mc-text-center"><a href="sign-in.html" class="ui-btn ui-corner-all ui-shadow ui-btn-b mc-top-margin-1-5">ok</a></div>
</div>
</div>
</div><!-- /content -->
</div><!-- /page -->
then, go to the cordova-project/www/index.html file and paste the code immediately below the page-signin page. make sure to modify the page’s id attribute and the header div as shown below:
<div data-role="page" id="page-signup">
<div class="bi-header" data-role="header" data-theme="c" data-position="fixed" data-tap-toggle="false">
<a href="#page-index" data-icon="home" data-iconpos="notext" data-transition="slide" data-direction="reverse"></a>
<h1>bookit</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>sign up</h3>
<div id="ctn-err" class="bi-invisible"></div>
<label for="txt-first-name">first name</label>
<input type="text" name="txt-first-name" id="txt-first-name" value="">
<label for="txt-last-name">last name</label>
<input type="text" name="txt-last-name" id="txt-last-name" value="">
<label for="txt-email-address">email address</label>
<input type="text" name="txt-email-address" id="txt-email-address" value="">
<label for="txt-password">password</label>
<input type="password" name="txt-password" id="txt-password" value="">
<label for="txt-password-confirm">confirm password</label>
<input type="password" name="txt-password-confirm" id="txt-password-confirm" value="">
<!--<a href="#dlg-sign-up-sent" data-rel="popup" data-transition="pop" data-position-to="window" id="btn-submit" class="ui-btn ui-btn-b ui-corner-all mc-top-margin-1-5">submit</a>-->
<button id="btn-submit" class="ui-btn ui-btn-b ui-corner-all mc-top-margin-1-5">submit</button>
<div data-role="popup" id="dlg-sign-up-sent" data-dismissible="false" style="max-width:400px;">
<div data-role="header">
<h1>almost done...</h1>
</div>
<div role="main" class="ui-content">
<h3>confirm your email address</h3>
<p>we sent you an email with instructions on how to confirm your email address. please check your inbox and follow the instructions in the email.</p>
<div class="mc-text-center"><a href="sign-in.html" class="ui-btn ui-corner-all ui-shadow ui-btn-b mc-top-margin-1-5">ok</a></div>
</div>
</div>
</div><!-- /content -->
</div><!-- /page -->
we also added a back button to the header section of this page to allow users to navigate back to the index page.
adding the registration succeeded page
the last page that we will migrate is the registration succeeded page. open the registration-succeeded.html file in the project’s root directory and copy the jquery mobile page:
<div data-role="page" data-bookit-page="signup-succeeded">
<div data-role="header" data-theme="c">
<h1>book it</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h2 class="mc-text-center">registration succeeded</h2>
<p class="mc-top-margin-1-5">congratulations! you are now registered with bookit.</p>
<a href="sign-in.html" class="ui-btn ui-btn-b ui-corner-all">sign in</a>
<p></p>
</div><!-- /content -->
</div><!-- /page -->
place the code in the cordova-project/www/index.html file, immediately below the page-signup page. then update the page’s id to page-signup-succeeded as shown below:
<div data-role="page" id="page-signup-succeeded">
<div data-role="header" data-theme="c">
<h1>book it</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h2 class="mc-text-center">registration succeeded</h2>
<p class="mc-top-margin-1-5">congratulations! you are now registered with bookit.</p>
<a href="#page-signin" class="ui-btn ui-btn-b ui-corner-all">sign in</a>
<p></p>
</div><!-- /content -->
</div><!-- /page -->
this concludes the migration of the application’s jquery mobile pages into the cordova project. next, we will migrate the javascript files.
migrating the javascript files into the cordova project
we are going to start the javascript files migration by creating the directories for the libraries that we will use in the cordova project.
create the lib directory in the cordova-project/www directory. then, create the lib/fastclick, lib/jqm and lib/jquery directories:
adding the library files
now, download the fastclick library and place it in its directory. do the same with jquery mobile and jquery.
adding the applications file
the second step consists of adding the application files. copy the api-messages.js and settings.js files from the project’s root folder and paste them into the cordova-project/www/js directory:
be mindful of the value that you assign to the signupurl variable in the setttings.js file. when you are testing the app, this url should point to your express server instance (we created the server in the using mongodb and mongoose for user registration, login and logout in a mobile application chapter of this series). when we move the app to production, this url should point to our public express server endpoint.
creating the controller module
as a third step, we are going to refactor the code in the index.js file. what we want is to create javascript classes that will implement different features of the app, starting with the user signup feature.
the features’ core logic will reside in these classes, separate from each other and from the jquery mobile page lifecycle events.
this change will make the application more maintainable. it will be easier for multiple developers to work on different areas of the app, and it will be easier to create unit tests for the different features.
we will start the refactoring of the signup code by creating the the signup-controller.js file in the cordova-project/www/js directory:
we will define a signupcontroller class in the file:
var bookit = bookit || {};
bookit.signupcontroller = function () {
this.$signuppage = null;
this.$btnsubmit = null;
this.$ctnerr = null;
this.$txtfirstname = null;
this.$txtlastname = null;
this.$txtemailaddress = null;
this.$txtpassword = null;
this.$txtpasswordconfirm = null;
};
the $signuppage, $btnsubmit, $ctnerr, $txtfirstname, $txtlastname, $txtemailaddress, $txtpassword and $txtpasswordconfirm variables will hold references to the html elements in the jquery mobile page that contains the signup form.
moving on to the implementation of the class, we first are going to add the init method:
bookit.signupcontroller.prototype.init = function () {
this.$signuppage = $("#page-signup");
this.$btnsubmit = $("#btn-submit", this.$signuppage);
this.$ctnerr = $("#ctn-err", this.$signuppage);
this.$txtfirstname = $("#txt-first-name", this.$signuppage);
this.$txtlastname = $("#txt-last-name", this.$signuppage);
this.$txtemailaddress = $("#txt-email-address", this.$signuppage);
this.$txtpassword = $("#txt-password", this.$signuppage);
this.$txtpasswordconfirm = $("#txt-password-confirm", this.$signuppage);
};
this method is where we obtain the references to the html elements in the jquery mobile page that contains the signup form.
next, the method that verifies that the values entered in the password and confirm password input elements match:
bookit.signupcontroller.prototype.passwordsmatch = function (password, passwordconfirm) {
return password === passwordconfirm;
};
then, the method where we check that the password is complex:
bookit.signupcontroller.prototype.passwordiscomplex = function (password) {
// todo: implement complex password rules here. there should be similar rule on the server side.
return true;
};
remember that in the previous chapter of this tutorial i left the implementation of the password complexity rules as homework for you.
we also need to add a method that checks that the value entered in the email address text field is formatted as an email address:
bookit.signupcontroller.prototype.emailaddressisvalid = function (email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-za-z\-0-9]+\.)+[a-za-z]{2,}))$/;
return re.test(email);
};
and a method to reset the signup form:
bookit.signupcontroller.prototype.resetsignupform = function () {
var invisiblestyle = "bi-invisible",
invalidinputstyle = "bi-invalid-input";
this.$ctnerr.html("");
this.$ctnerr.removeclass().addclass(invisiblestyle);
this.$txtfirstname.removeclass(invalidinputstyle);
this.$txtlastname.removeclass(invalidinputstyle);
this.$txtemailaddress.removeclass(invalidinputstyle);
this.$txtpassword.removeclass(invalidinputstyle);
this.$txtpasswordconfirm.removeclass(invalidinputstyle);
this.$txtfirstname.val("");
this.$txtlastname.val("");
this.$txtemailaddress.val("");
this.$txtpassword.val("");
this.$txtpasswordconfirm.val("");
};
we will invoke this method every time the user opens the signup page, making sure that any prior values entered in the form are cleared.
finally, the template method that will capture the registration data, send it to the server and process the server’s response:
bookit.signupcontroller.prototype.onsignupcommand= function () {
var firstname = this.$txtfirstname.val().trim(),
lastname = this.$txtlastname.val().trim(),
emailaddress = this.$txtemailaddress.val().trim(),
password = this.$txtpassword.val().trim(),
passwordconfirm = this.$txtpasswordconfirm.val().trim(),
invalidinput = false,
invisiblestyle = "bi-invisible",
invalidinputstyle = "bi-invalid-input";
// reset styles.
this.$ctnerr.removeclass().addclass(invisiblestyle);
this.$txtfirstname.removeclass(invalidinputstyle);
this.$txtlastname.removeclass(invalidinputstyle);
this.$txtemailaddress.removeclass(invalidinputstyle);
this.$txtpassword.removeclass(invalidinputstyle);
this.$txtpasswordconfirm.removeclass(invalidinputstyle);
// flag each invalid field.
if (firstname.length === 0) {
this.$txtfirstname.addclass(invalidinputstyle);
invalidinput = true;
}
if (lastname.length === 0) {
this.$txtlastname.addclass(invalidinputstyle);
invalidinput = true;
}
if (emailaddress.length === 0) {
this.$txtemailaddress.addclass(invalidinputstyle);
invalidinput = true;
}
if (password.length === 0) {
this.$txtpassword.addclass(invalidinputstyle);
invalidinput = true;
}
if (passwordconfirm.length === 0) {
this.$txtpasswordconfirm.addclass(invalidinputstyle);
invalidinput = true;
}
// make sure that all the required fields have values.
if (invalidinput) {
this.$ctnerr.html("<p>please enter all the required fields.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
return;
}
if (!this.emailaddressisvalid(emailaddress)) {
this.$ctnerr.html("<p>please enter a valid email address.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
this.$txtemailaddress.addclass(invalidinputstyle);
return;
}
if (!this.passwordsmatch(password, passwordconfirm)) {
this.$ctnerr.html("<p>your passwords don't match.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
this.$txtpassword.addclass(invalidinputstyle);
this.$txtpasswordconfirm.addclass(invalidinputstyle);
return;
}
if (!this.passwordiscomplex(password)) {
// todo: use error message to explain password rules.
this.$ctnerr.html("<p>your password is very easy to guess. please try a more complex password.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
this.$txtpassword.addclass(invalidinputstyle);
this.$txtpasswordconfirm.addclass(invalidinputstyle);
return;
}
$.ajax({
type: 'post',
url: bookit.settings.signupurl,
data: "email=" + emailaddress + "&firstname=" + firstname + "&lastname=" + lastname + "&password=" + password + "&passwordconfirm=" + passwordconfirm,
success: function (resp) {
if (resp.success === true) {
$.mobile.navigate("#page-signup-succeeded");
return;
} else {
if (resp.extras.msg) {
switch (resp.extras.msg) {
case bookit.apimessages.db_error:
case bookit.apimessages.could_not_create_user:
// todo: use a friendlier error message below.
this.$ctnerr.html("<p>oops! bookit had a problem and could not register you. please try again in a few minutes.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
break;
case bookit.apimessages.email_already_exists:
this.$ctnerr.html("<p>the email address that you provided is already registered.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
this.$txtemailaddress
.addclass(invalidinputstyle);
break;
}
}
}
},
error: function (e) {
console.log(e.message);
// todo: use a friendlier error message below.
this.$ctnerr.html("<p>oops! bookit had a problem and could not register you. please try again in a few minutes.</p>");
this.$ctnerr.addclass("bi-ctn-err").slidedown();
}
});
};
note how we implemented this class so it doesn’t have any direct ties to the jquery mobile page lifecycle events, or to the jquery mobile page that contains the sign up form. its only connection with the page is indirect, through the variables that hold references to the html elements of the form.
modifying the index.js file
now we are going to turn our attention to the cordoba-project/www/js/index.js file, where we need to invoke the signupcontroller class that we just created. at this point, this file only contains the starter code generated when we created the cordova project.
let’s open the file and replace its code with the code below.
var bookit = bookit || {};
// begin boilerplate code generated with cordova project.
var app = {
// application constructor
initialize: function () {
this.bindevents();
},
// bind event listeners
//
// bind any events that are required on startup. common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindevents: function () {
document.addeventlistener('deviceready', this.ondeviceready, false);
},
// deviceready event handler
//
// the scope of 'this' is the event. in order to call the 'receivedevent'
// function, we must explicitly call 'app.receivedevent(...);'
ondeviceready: function () {
app.receivedevent('deviceready');
},
// update dom on a received event
receivedevent: function (id) {
}
};
app.initialize();
// end boilerplate code.
$(document).on("mobileinit", function (event, ui) {
$.mobile.defaultpagetransition = "slide";
});
app.signupcontroller = new bookit.signupcontroller();
$(document).delegate("#page-signup", "pagebeforeshow", function () {
// reset the signup form.
app.signupcontroller.resetsignupform();
});
$(document).delegate("#page-signup", "pagebeforecreate", function () {
app.signupcontroller.init();
app.signupcontroller.$btnsubmit.off("tap").on("tap", function () {
app.signupcontroller.onsignupcommand();
});
});
the first block of code in the file is part of the boilerplate code that was already there, generated when we created the cordova project. we will leave it in place for now.
after the boilerplate code, we use the mobileinit handler to set the jquery mobile application’s default page transition to slide. i think that the slide transition gives the navigation a more native feel:
$(document).on("mobileinit", function (event, ui) {
$.mobile.defaultpagetransition = "slide";
});
next, we create the signupcontroller property in the app object, and assign it an instance of the signupcontroller class:
app.signupcontroller = new bookit.signupcontroller();
at this point we are ready to create the handlers for the jquery mobile page lifecycle events that we are interested in, the first of which is pagecontainerbeforeshow:
$(document).on("pagecontainerbeforeshow", function (event, ui) {
if (typeof ui.topage == "object") {
switch (ui.topage.attr("id")) {
case "page-signup":
// reset the signup form.
app.signupcontroller.resetsignupform();
break;
}
}
});
we use the pagecontainerbeforeshow event to reset the fields of the signup form. it’s possible for a user to visit this page multiple times. for security reasons, we want to clear any prior entries before we show the form to the user.
the second page event that we want to intercept is the beforecreate event:
$(document).delegate("#page-signup", "pagebeforecreate", function () {
app.signupcontroller.init();
app.signupcontroller.$btnsubmit.off("tap").on("tap", function () {
app.signupcontroller.onsignupcommand();
});
});
we use the pagebeforecreate event to hook our tap handler for the submit button. the handler invokes the signupcontroller’s onsignupcommand method, which validates the user’s input, sends the registration request to the server and processes the server’s response.
this concludes the migration of the application’s core logic over to the cordova project. we also moved the input validation and user registration logic into the singupcontroller class, in the signup-controller.js file. we left the logic that hooks the jquery mobile page events in the index.js file. this logic invokes the signupcontroller’s methods as needed.
let’s test the app to make sure the user signup process works.
choices for testing a cordova app
i prefer to test my android apps using either ripple (double-check the link, i noticed that it changes over time), genymotion , or my own development devices. in this article i will show you how to test with genymotion and your own device.
testing a cordova application with genymotion
to test your application with genymotion, follow these steps:
- install and configure genymotion. then, add the virtual devices that you want to test the app on. the instructions on how to do this are available in genymotion’s dev zone .
- start the genymotion virtual device that you want to test on.
- start your mongodb instance if it isn’t already running.
-
open a command window in the [project root]/server directory and run the following command to start your express server:
node index.js
-
open acommand window and run the following cordova command to build and deploy the application to the virtual device:
cordova run android --device
when the last step finishes, the application will execute on the virtual device.
testing a cordova app on a physical device
to test your application on a device, follow these steps:
- set up your device for development. the instructions on how to do this are available in the android’s developer website .
- connect your device to your development computer with a usb cable.
-
open a terminal/command window in the [project root]/server directory and run the following command to start your express server:
node index.js
-
open a terminal/command window and run the following cordova command to build and deploy the application to the device:
cordova run android --device
summary and next steps
in this article we transformed a jquery mobile web application into a jquerymobile + cordova native application that can be deployed to mobile devices. we went through the process of creating a cordova project, migrating a jquery mobile application into it, and deploying the mobile application to a device.
in the next article of this series of mobile development tutorials, we will continue building the features of the meeting room manager app that is the subject of this series. next up is the user login feature. make sure to sign up for my newsletter so you can be among the first to know when the next article is online.
download the source code
download the source code for this tutorial here: jquery mobile and cordova tutorial on github
all the chapters of this series
you can find all the published parts of this series here: the meeting room booking app tutorial .
Published at DZone with permission of Jorge Ramon, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments