Intel XDK App Programming Full Course Handout
Intel XDK App Programming Full Course Handout
Intel XDK App Programming Full Course Handout
Unit 1:
Unit 1: Introducing the Course
About the Course
Fast Track to Intel XDK New is designed to
teach experienced web developers and
designers how to design, implement, and
package web applications for mobile devices.
The corse is task!based, with "o learning b"
performing a series of hands!on tasks. #ver the
next for hors "o will create a web
application named $Friends with %eer& that
enables sers to create a themed contact
manager that ses man" mobile!specific
featres sch as calclating geoposition, video
pla"back, psh notifications, phone dialing,
sending emails, and more'
(long with covering the basics of the Intel
XDK New, the corse focses on best practices
and design, stressing the importance of
sabilit", optimi)ation, and maintainabilit" of
cross!device compatible applications.
*ab instrctions are designed for +indows or
#,-X sers who have an (ndroid phone.
2013 Intel Corporation 1 - 1
Figure 1: The app
that you'll build in this
course.
Fast Track to Intel XDK New
Introducing Intel XDK New
Intel. XDK N/+, enables "o to easil" create, test, and package cross!
device compatible 0T1*2!based mobile apps. Intel XDK New rns on
+indows 3,4, #,-X and 5bnt *inx desktops. It seamlessl" integrates
man" best!of!breed mobile web development technologies into an eas"!to!
se, integrated development environment.
Choose a Framework
6o can develop "or apps sing poplar 0T1*2 mobile
frameworks inclding
Bootstrap 7 a poplar front!end framework for faster
and easier web development.
jQuery Mobile 7 the $write less, do more& librar" for
rapidl" coding mobile apps.
Intel's App Framework ! an open sorce 0T1*2 5I
framework
Topcoat 7 a fast!performing 8,, framework from (dobe that incldes
icons, fonts, and themed components for mobile devices.
1 - 2 2013 Intel Corporation.
Figure 2: The Intel XDK New !I
Unit 1: Introdcin! t"e Corse
Develo visuall!" code #ast and #uriousl!
Intel. XDK N/+ integrates an eas"!to!se, drag 9 drop app designer
with Brackets, a highl"!regarded, open!sorce editor with s"ntax helpers
and ato!completion.
$mulate oular devices
5se the bilt!in Apache Ripple device emlator to simlate "or app
rnning on mltiple devices, from different geographic locations, var"ing
bandwidth conditions, and changing orientations. 5se the integrated
Google hrome !e" Tools to trobleshoot rntime isses.
2013 Intel Corporation. 1 - 3
Figure ": The integrated #rac$ets code editor.
Figure %: !sing the built&in de'ice e(ulator.
Fast Track to Intel XDK New
%rust" &ut 'eri#!
%" loading Intel App #re"iew onto "or mobile devices, "o:ll be able to
easil";
<n "or app on ph"sical devices withot rebilding
Debg "or app while it:s rnning on the device, sing the integrated
weinre remote debgger.
8ondct performance profiling
8heck ot demo apps.
Intel (pp =review is available for i#,, (ndroid, and +indows =hone.
1 - # 2013 Intel Corporation.
Figure ): Test your app on physical de'ices with Intel *pp +re'iew
Unit 1: Introdcin! t"e Corse
(ackage #or A )tores
(fter "o:ve completed "or testing, se Intel XDK:s integrated (pache
8ordova framework to bild native apps for all the poplar mobile
platforms.
Integrate native #eatures and add cloud suort
The Intel XDK (=I that incldes featres not crrentl" available in
8ordova, inclding;
Facebook login (=I
(ndroid mlti!toch
#ath spport
/nhanced adio
(ccelerated canvas
In addition, "o can >ickl" add clod!based featres from appMobi to
sch as psh notification spport, ser management, e!commerce, and
clod hosting.
2013 Intel Corporation. 1 - $
Fast Track to Intel XDK New
*eviewing the Course +b,ectives
(fter completing this corse, "o shold be able to;
Develop web and native apps for mobile devices
?isall" design and implement a graphical ser interface.
8reate inpt forms that read and sbmit data to-from an application
server
<e>est @,#N data from an application server
Integrate mapping, geolocation, and psh notifications into a mobile
app.
Deplo" adio and video assets
Theme "or application to meet branding standards
Test and package "or app to rn nativel" on (ndroid and i=hone
devices.
*eviewing the Course (rere-uisites
The knowledge prere>isites for this corse are;
=rior experience with 0T1* 2
( casal nderstanding of 8,,
Intermediate @ava,cript coding skills and, in particlar, familiarit" with
@ava,cript #bAect Notation
*e-uired )o#tware
The following software is </B5I</D to be installed on "or compter;
Intel $!%
http;--xdk!software.intel.com-
Fast Track to Intel $!% stu&ent 'iles
http;--www.xdktraining.com-stdent.)ip
The following software is </B5I</D to be installed on "or mobile
device;
Intel App #re"iew
(vailable on i#,, (ndroid, and 1icrosoft stores.
1 - % 2013 Intel Corporation.
Unit 1: Introdcin! t"e Corse
*eviewing the Course Format
This corse is divided into ten nits, each of which presents new
information and contains demonstrations, walkthroghs, and a lab. (t the
end of each nit, "o will find a smmar" and a short review to test "or
knowledge of the nitCs content.
The following icons are sed throghot the gide;
oncepts introdce new information.
!emonstrations illstrate new concepts.
(alkthroughs gide "o, with the instrctorCs assistance, throgh
procedres in a hands!on context.
)abs let "o practice new skills on "or own.
*ummaries provide a brief s"nopsis of the nitCs content.
Re"iews test how well "o remember the concepts from the nit.
Best #ractices provide "o with helpfl insights and information.
2013 Intel Corporation. 1 - &
Fast Track to Intel XDK New
+utlining the Course Content
+nit ,- Intro&ucing the ourse
+nit .- Getting *tarte&
Introdcing the Intel XDK New
<eviewing the featres and benefits of 0T1*2 - 8,,D
5sing Debgging Techni>es
Eetting 0elp
+nit /- !esigning 0iews
Defining =ages
5sing *a"ot 8ontrols
*inking to =ages
(dding text and images
+nit 1- (orking with !ata
5sing ABer" to make data re>ests via (@(X
#tptting strctred data into a *ist
<eading Data from the 8ontact:s list
,toring data on the Device with +eb,B*
+nit 2- Implementing Forms
5sing the Forms +idgets
Implementing Data ?alidation
,aving Form Data
+nit 3- Implementing G45 Features
Eeocoding (ddresses
(c>iring the Device =osition
8alclating Distance to Targets
?isali)ing Data on a 1ap
1 - ' 2013 Intel Corporation.
Unit 1: Introdcin! t"e Corse
+nit 6- +sing !e"ice Features
Dialing the =hone
,ending /mail
*anching Trn %" Trn Directions
5sing the (ccelerometer
0andling =sh Notifications
+nit 7- 8an&ing Multime&ia
5nderstanding the featres and capabilities of 0T1*2
=la"ing (dio
=la"ing ?ideo
+nit 9- Theming your App
5sing 8,,D Featres and 8apabilities
(ppl"ing 8,,D %ackgronds
5sing Theme<oller to theme "or 5I components
+nit ,:- Going ;ati"e
8reating =rodction +eb %ilds
8reating Native %ilds for i#,
/xercise; =ackaging a Native i#, %ild
2013 Intel Corporation. 1 - (
Fast Track to Intel XDK New
Demonstration 1.1: 'iewing the Alications
#bserve as "or instrctor introdces the applications that "o will be
bilding dring the exercises;
6o will bild the Friends with %eer mobile application dring "or
instrctor!led walkthroghs in the following order;
(bot Friends with %eer F0ome =ageG
%eer *ist
Friends with %eer 8ontact *ist
Friends with %eer 8ontact Data /ntr" Form
Friends with %eer 8ontact Detail
Friends with %eer ?ideo
*eviewing the Alication / Intro )creens
The Friends with %eer 8ome #age
contains simple html markp. It:s
designed to help "o get comfortable
sing the Intel XDK visal designer.
The Beers )ist displa"s a list of
beers that were downloaded from a
</,T!based web service and
cached into an 0T1*2 +eb,B*
database.
1 - 10 2013 Intel Corporation.
Unit 1: Introdcin! t"e Corse
The ontact )ist is driven from data
stored in a +eb,B* database. 8licking
on the btton in the top!left corner
enables "o to import data from "or
phone:s native contacts app. 5sers can
actall" shake the device to select a
friend at random.
The ontact 'orm enables "o to
edit information abot "or
contacts. It also converts their
street address to a lat-lng position
on!the!fl" and has client!side data
validation.
2013 Intel Corporation. 1 - 11
Fast Track to Intel XDK New
*eviewing the Alication / Using Device Features
The Friends with %eer !etail #age
enables the ser to activate the device:s
phone dialer, email application, and
navigation app. It also ses Eoogle
1aps to displa" real!time traffic
conditions arond "or friend:s
location.
The 0i&eo page displa"s a
streaming video from ?imeo and
an mpH from a web server so that
the ser will never have to feel like
the":re drinking alone.
1 - 12 2013 Intel Corporation.
Unit 1: Introdcin! t"e Corse
0alkthrough 1.1: Installing the Courseware
In this lab, "o will perform the following tasks;
Install Intel XDK New on "or desktop
Install Intel (pp =review on "or mobile device
Download and install the corse files
)tes
Download and Install Intel XDK
I. #pen a web browser to the following 5<*;
http;--xdk!software.intel.com-
J. 8lick the Download Intel XDK New btton.
+)1X Users:
D. #pen the downloaded .dmg file
H. Doble!click on the .pkg file
2. 8omplete the steps in the installation wi)ard.
K. ,elect Go L Applications and verif" that $!% New is present.
2icroso#t 0indows 34 Users:
3. #pen the downloaded .exe file
4. 8omplete the steps in the installation wi)ard
M. ?erif" that Intel $!% New appears in "or ,tart men.
5og into Intel XDK
IN. *anch Intel $!% New
II. 8lick on ;ee& to sign up 'or an Account<
IJ. Fill ot the form, entering "or name, email address, password, and
contr". Note the following;
=asswords mst be between 4!I2 characters in length
=asswords mst contain at least one alpha character
=asswords ma" not contain non!/nglish characters
=asswords mst contain at least one nmber
=asswords mst contain at least one special character F'OPQRG
ID. 8heck the Terms an& on&itions checkbox.
IH. ,ign p for the newsletters.
2013 Intel Corporation. 1 - 13
Fast Track to Intel XDK New
I2. 8lick the *ubmit btton.
IK. /nter "or sername and password.
I3. Trn on the checkbox labeled %eep me logge& in on this computer.
I4. 8lick *ubmit.
Install Intel A (review on !our 2obile Device
IM. 8onfigre "or mobile device to be on the same wireless network as
"or compter.
JN. #pen Eoogle =la" on "or (ndroid phone.
JI. ,earch for $Intel App #re"iew&
JJ. Tap on Intel App #re"iew
JD. Tap on the Install btton.
JH. Tap the Accept btton.
J2. +hen the installation process as completed, tap the open btton.
JK. ,ign into the app sing the Intel XDK credentials that "o created
earlier in this exercise.
Download and Un6i the $7ercise Files
J3. Download the exercise files from
http;--www.xdktraining.com-exercises.)ip
J4. 5n)ip the files into "or home-docments folder.
7 /nd of +alkthrogh !!
1 - 1# 2013 Intel Corporation.
Unit 1: Introdcin! t"e Corse
Unit )ummar!
The corse is presented throgh a combination of lectres and hands!
on exercises.
The corse has been designed assming that "o alread" nderstand
0T1*, 8,,, and some @avascript.
The corse consists of IN nits that cover the essentials of developing
mobile apps with Intel XDK New.
The corse focses on developing web and native applications for
mobile devices.
6o will bild a web application to keep track of "or friends with
beer.
2013 Intel Corporation. 1 - 1$
(This page intentionally leIt blank)
Unit 2:
Getting Started with Intel XDK New
Unit Objectives
After completing this unit, you should be able to:
Understand the features and capabilities of Intel XDK New
Use the visual designer to create a !ello "orld# page in your app$
Use the code editor to add %ava&cript to your app$
'est your app on the simulator and your mobile device$
(ac)age your app as a native application for distribution on App stores$
Unit Topics
Introducing Intel XDK New
Debugging *our Apps
+etting !elp
2 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Introdcing Intel XDK New
'he Intel, XDK NEW development system is for those developers who
wish to use their !'-./ e0pertise to build hybrid !'-./ apps for
mobile devices 1e$g$, phones and tablets2 and other platforms that host
!'-./ web apps 1such as a +oogle 3hrome4 e0tension or a mobile web
site2$
Going with an !T"# $ Soltion
Developers and corporate I' increasingly turn to !'-./ as a solution to
meet the critical, time5sensitive demands of their organi6ations$
Developing mobile apps with !'-./ offers several )ey advantages over
native app development:
Native apps are developed to run on a single device platform whereas
!'-./ apps use the same codebase to run on multiple devices and
operating systems$
Native apps are typically distributed via app stores, however, !'-./
apps can also be deployed as mobile web sites that run in a user7s
mobile web browser$
!'-./ apps use open5source technologies$
Native 8& apps can get lost# among the hundreds of thousands of
apps in app stores$ -obile web apps are crawlable# by search engines$
-obile web apps are instantly updatable on a web server$
Instead of having to learn %ava or 8b9ective53, web developers can
leverage their e0isting s)ill sets to rapidly create mobile apps$
!'-./5based apps tend to be less affected by changes in the mobile
operating system$
Navigating the Tooling %ag&ire
!istorically, one of the biggest challenges faced by mobile web app
developers has been dealing with the lac) of a truly integrated development
environment$ -ost developers spend their days toggling between an html
design tools, a 9avascript code editor, a 3&& editor, web browser,
debugger, command5line build utilities, :'(, mobile simulators, and more$
Intel XDK NEW is the first truly integrated development environment that
application consists of a set of best5of5breed tools that help you code,
debug, test and build mobile web apps and hybrid !'-./ apps for
multiple target platforms$
2 - 2
2013 Intel Corporation.
Getting tarte! wit" Intel XDK New
'eviewing the Intel XDK New Inter(ace
Intel XDK New is organi6ed around the se;uence that !'-. app
developers follow when they create and pac)age an application:
<$ Develop
Use the visual designer to prototype your graphical user interface and
handle user interactions by hand5coding 9avascript with the built5in
=rac)ets editor$
>$ Emulate
?alidate that your application loo)s and functions properly across
multiple screen resolutions, under varying bandwidth conditions, and
from different geographic locations by using the embedded Apache
@ipple emulator$ Debug application errors with the integrated +oogle
debugger$
A$ Test
?erify that your app performs as e0pected by running from Intel7s App
(review container$ Debug the app and chart its performance as it runs
on your device by using the embedded weinre remote debugger$
B$ Build
(ac)age the app for distribution via app stores or the web using the
integrated Apache 3ordova tool)it$ 'est device5specific features$
/$ Services
Integrate cloud5based services into your app from app-obi, including
push5notifications, e5commerce, live updates, in5app purchasing, and
hosting$
2 - 3
2013 Intel Corporation.
Fast Track to Intel XDK New
Designing )pps
As depicted in :igure <, Develop mode enables you to visually prototype
the loo) and feel of your application$
'he Project Selector enables you to load pre5e0isting pro9ects or
create new pro9ects into the Intel XDK +UI$
*our app7s views appear in the Project Files panel$
"hile in Design view, you can drag and drop components from the
UI Controls Palette onto the Design Canvas$
UI controls that you7ve dropped onto the Design 3anvas may be
configured by changing settings in the Property Editor$
'he Product Version indicator alerts you as to the release version
of the XDK that is currently in use$
2 - #
2013 Intel Corporation.
Figure 1 Develop ! Design Vie"
Getting tarte! wit" Intel XDK New
Developing )pps
As depicted in :igure >, toggling to 3ode view enables you to modify the
code generated by the visual designer, as well as edit 9avascript and css
application assets$ 3ode hints appear as you type$
'nning *or )pp in an +&lator
As illustrated in :igure A, clic)ing on the Cmulate tab runs your app in the
Apache @ipple emulator$
'he emulator enables you to simulate your app running on multiple devices
under varying environmental conditions:
2 - $
2013 Intel Corporation.
Figure # Using t$e integrated Brac%ets editor to $and&code your app
Figure ' Simulate your app running on multiple devices(
Fast Track to Intel XDK New
'he Devices panel allows you to simulate your app running on a
variety of popular devices including the i(ad, i(hone, +oogle Ne0us,
-icrosoft &urface (ro, -otorola Droid >, No)ia .umina D>E,
&amsung +ala0y &, and &amsung +ala0y tab$
'he In)ormation panel provides
you with metrics regarding your
selected device, including 8&,
screen resolution, pi0el density, and
the http user agent that7s transmitted
on each re;uest$
'he *ccelerometer panel enables
you to simulate moving the device
along its 0, y, and 6 a0is$ 'his is
vital for testing movement5based
controls$ *ou can also have it
virtually sha)e# the device$
'he +ive Update Service panel
simulates your app receiving an
update service re;uest from
app-obi$
'he Device , -et"or% Settings
panel enables you to simulate
different degrees of networ)
throughput 1from "i:i to no
connection2, as well as toggle locales from Cnglish to :rench or
+erman$
'he .eo +ocation panel allows you to simulate how your app would
behave if it were running from different physical locations$ *ou can
also configure heading, speed, altitude, +(& accuracy, and +(&
timeout$ *ou can even have it replay a route that was saved to a +(&
C0change :ormat 1+(X2 file$
'he Pus$/o0i panel allows you to inspect how your application
would behave if it received a push5notification message$
2 - %
2013 Intel Corporation.
Figure 1 Testing accelerometer&
0ased controls(
Getting tarte! wit" Intel XDK New
Testing ,or app on a device
'he 'est module, depicted in :igure /, enables you to easily upload your
application to a testing server$ *ou can then launch it on any device that7s
running the Intel App (review mobile application$
*ou7ll typically test apps on physical devices
by completing the following steps:
<$ In Intel XDK New, clic) on the 'est tab$
>$ 3lic) on the Pus$ Files button
A$ 8pen Intel *pp Previe" on your mobile
device$
B$ 'ap on the Server *pps tab$
/$ 'ap on the camera icon, located in the
top5right corner of the app$
F$ &can the G@ code in the XDK with your
phone7s camera$
8nce the G@ code has been scanned, the app
will be automatically downloaded and
e0ecuted$
*ou can debug the app as it7s running on your
device by using the built5in weinre remote
debugger$
2 - &
2013 Intel Corporation.
Figure 2 Upload your app and test it on devices using Intel *pp Previe"
Figure 3 Intel *pp Previe"
Fast Track to Intel XDK New
Generating -rodction .ilds
'he =uild tab, as depicted in :igure H, uploads your app to a cordova5
based build server, pac)aging your code as a native app for distribution
across popular app stores or for distribution within your enterprise$ 8ptions
include:
i8& Ad5!oc
Distribution
"indows I &tore
i8& App &tore
"indows (hone I
Ama6on
Android
'i6en
Noo)
2 - '
2013 Intel Corporation.
Figure 4 Intel 5D6 uses *pac$e Cordova to convert your "e0 app into
native apps )or all popular plat)orms(
Getting tarte! wit" Intel XDK New
As illustrated by :igure I, some vendors will re;uire you to upload
distribution certificates andJor supply authentication credentials$
*ou can also have XDK New create a distribution pac)age for deployment
across the following web platforms:
7e0*pp
Cnables you to post your code on a local or remote web server, or host
in App-obi$ 1*our code may be downloaded as a $6ip file2
C$rome
(ac)ages your app for distribution in the +oogle 3hrome store$
Face0oo%
(ac)ages your app for distribution via the :aceboo) social networ)$
2 - (
2013 Intel Corporation.
Figure 8 Uploading certi)icates and a provisioning pro)ile )or an i9S *pp
Store production 0uild
Fast Track to Intel XDK New
Using /lod Services
As illustrated by :igure D, Intel XDK New features tight integration with
app-obi cloud services$
"hile you are not obligated to use app-obi, it is a convenient resource for
providing the following application support resources:
:ost/o0i can host your app in a (!(, $NC', or Node$9s server
environment$ Cdge5cached hosting delivers the best performance for
on5the5go web apps, and host-obi provides that through our
partnership with Ama6on7s Clastic 3omputing 3loud, 1which now
spans the entire globe2$
+ive Update enables you to notify users that a new version of your
app is available$ *ou have the option to push app updates immediately
instead of waiting for your users to upgrade at their leisure$
Storevie" is a cloud5based reporting service that aggregates detailed
app analytics from the most popular app stores and displays them in an
interactive dashboard$
Pus$mo0i enables you to send push notifications to your subscribers$
*ou can target messages to a particular user target users based on
search filters$
1Touc$ is an in5app purchase 1IA(2 cloud service, that allows you to
interface with various app stores using a single line of 9avascript$
<'ouch ta)es away the pain of integrating with the various app stores
and payment providers$ "ith a single function call you can sell in5app
items on I8&, Android, "indowsI, "indowsI (hone, :aceboo) and
the 3hrome &tore$
2 - 10
2013 Intel Corporation.
Figure ; Using t$e app/o0i $osting service
Getting tarte! wit" Intel XDK New
0al1throgh 223: Getting Started
In this lab, you will perform the following tas)s:
.og into Intel XDK
3reate a new pro9ect
Design a hello world# page
'est your app in the emulator
(ac)age your app for distribution
Install your app on your Android device
Steps
/reate a New -roject
<$ .aunch Intel XDK New
>$ 3lic) on the Start a -e" Project button
A$ 3lic) on Start "it$ *pp Designer
B$ Cnter a pro9ect name of -y!ello"orld#
/$ 3lic) the Create button$
F$ 3lic) the -o T$an%s button$
H$ 3lic) the +et<s .o= button$
I$ In the left panel, clic) on inde0$html$ 'he &elect a :ramewor)# dialog
bo0 will appear$
D$ 3lic) on the j>uery /o0ile radio button$
<E$ 3lic) on the Select button$
Design a -age
<<$ :rom the 3ontrols panel, drag a !eader and drop it onto the design
canvas$
<>$ In the !eader &ettings panel, turn on the chec)bo0 ad9acent to the 'itle
property and enter the following title:
Friends with Beer
<A$ 'urn on the Fi?ed chec)bo0$
<B$ :rom the Controls @ /edia panel, drag a Te?t control and drop it
underneath the :eader on the Design canvas$
2 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
</$ In the 'e0t &ettings panel, change the te0t to the following:
Welcome to Friends with Beer!
Displa, ,or page in the +&lator
<F$ 3lic) on the Emulate tab$
<H$ In the Devices panel, select .oogle -e?us 1$
<I$ In the Devices panel, toggle the orientation of the emulated device by
clic)ing on the landscape orientation button$
<D$ In the Device , -et"or% Settings panel, note that you can emulate
different networ) lag conditions$
'n *or )pp on *or "obile Device
>E$ 3lic) on the Test tab$
><$ 3lic) the Sync button$
>>$ 8pen Intel *pp Previe" on your mobile device$
>A$ 'ap the Server *pps button$
>B$ 'ap the Camera button located in the top right corner of the +UI$
>/$ &can the G@ code on your des)top$
>F$ 'ap 96$ *our app should launch$
.ild ,or )pp (or Native Distribtion
>H$ @eturn to XDK New on your des)top$
>I$ 3lic) the Build tab$
>D$ 3lic) the *ndroid Build button$
AE$ 3lic) the Build *pp -o" button$
A<$ 3lic) the Do"nload Build button and save the generated $ap) file to
your des)top$
A>$ Cmail the $ap) file to yourself$
AA$ 8pen the email on your Android phone$
AB$ 'ap on the $ap) file attachment$
A/$ 3lic) on the Install button$
AF$ 3lic) 9pen$ *our app should open$
Congratulations( Aou<ve just 0uilt a native mo0ile app=
2 - 12
2013 Intel Corporation.
Getting tarte! wit" Intel XDK New
Debgging *or )pps
As you develop your apps, you7ll inadvertently insert bugs into your
program which will need to be eradicated as ;uic)ly and efficiently as
possible$ -ost of your bugs will li)ely appear when you run your app in
the emulator$ 8thers may not show up until you run the app on a physical
device$ :ortunately, XDK New has both of these scenarios covered$
Debgging in the +&lator
Intel XDK New
features an integrated
3hromium developer
that you can invo)e by
clic)ing the debugger
button from Cmulate
mode, as depicted in
:igure <E$
'he debugger enables
you to inspect the
D8- of your
application, review all
!''( re;uests, read the contents of coo)ies and !'-./ local storage, and
can even provide hints as to how to optimi6e your application7s
performance$
-ost importantly, it enables you to set brea)points and step through your
code interactively while monitoring the contents of variables$
2 - 13
2013 Intel Corporation.
Figure 11 T$e integrated C$romium de0ugger(
Figure 1B *ctivating t$e De0ugger
Fast Track to Intel XDK New
'he debugger is partitioned into the following seven segments:
+a0el Description
Elements Cnables you to clic) on any area in your browser and
inspect its mar)up$ It also displays all the 3&& applied to
the element and allows you to selectively enable, disable,
and modify individual styles$
Resources Cnables you to review the contents of !'-./ local
database 1&;l.ite2, !'-./ .ocal &torage, !'-./ &ession
&torage, !''( coo)ies, and the !'-./ Application
3ache$
Network Displays all !''( communications$ 'his is particularly
useful for troubleshooting A%AX re;uests$ Displays both
data transmitted via the !''( header to the server as well
as the content returned from the server$
Sources Displays all of the %ava&cript files that were loaded into the
browser as part of the re;uest$ *ou can set breakpoints and
step through your code one line at a time$ *ou can also
define watch expressions to )eep an eye on the contents of
your variables$
Timeline Displays the time to download files from the server, the
time to e0ecute scripts, and the time to render the output$
Use the timeline to develop insights into where your
bottlenec)s might be in your code as well as benchmar)
your changes$
Profiles &imilar to the timeline, the Profiles panel captures the
e0ecution of your application and then displays the
percentage of 3(U utili6ation that was re;uired to e0ecute
specific methods or handle events$ *ou can also profile the
performance of your 3&& to see how long selector matching
too) and ta)e a heap snapshot to understand memory
distribution among your page7s %avascript ob9ects and
related D8- nodes$
Audits Cvaluates the performance of your application and provides
helpful optimi6ation tips$
Console Displays error messages as well as the output from
e0ecuting console(logCD statements$ *ou can also e0ecute
9avascript code interactively in this view$
2 - 1#
2013 Intel Corporation.
Getting tarte! wit" Intel XDK New
-rogra&&aticall, Setting .rea1points
*ou can set programmatic brea)points by inserting the following command
into your %ava&cript:
debugger;
If the 3hromium debugger is active when this statement is encountered,
e0ecution of your app will pause and your script will appear in the Sources
section as depicted in :igure <>2$
As depicted in :igure
<A, you can use the
debugger controls to
interactively step
through your code$
*ou can also set watch
expressions in order to
view how your code
changes the contents of
your variables$
2 - 1$
2013 Intel Corporation.
Figure 1# *ctive 0rea%point
Figure 1' Using t$e de0ugger<s step controls
Fast Track to Intel XDK New
Otptting 4ariables to the Debgger /onsole
Use the console$log12 command to dump the contents of %avascript
variables to the 3hromium debugger console as illustrated below:
<script type="application/javascript">
function init() {
$('#debugtn')!bind('clic"'# function(e) {
debugger$
for (var i=%$ i<&$ i'') {
console.log(i);
(
()$
(
</script>
-rogra&&aticall, Interacting with *or )pplication
'he 3hromium debugger can do far more than 9ust report errors and output
the results of console$log12 statements$ *ou can actually use it to interact
with your application in real5time, use it to e0periment with invo)ing
9avascript api methods, and change the contents of variables on5the5fly$
As depicted in figure </, you can even fire events on application elements
and see the result in the emulatorK
2 - 1%
2013 Intel Corporation.
Figure 11 Varia0les t$at are output via console(log appear in t$e C$romium
de0ugger Console vie"
Figure 12 Invo%ing application met$ods )rom t$e C$romium console vie"(
Getting tarte! wit" Intel XDK New
Debgging on the Device
If your application invo)es methods from the 3ordova A(I, or uses device
features that are not natively supported by %avascript, you may find
yourself in a situation when it7s most effective to troubleshoot the app when
it7s actually running on a physical device$
Using a des)top debugger to inspect an app running on a device is a
process called remote debugging$ @emote debugging is supported by the
Intel XDK via the weinre remote debugger$
:or remote debugging to wor) properly, you must:
<$ Cmbed the following code into your !'-. files:
<script
src="http://debugso!tw"re.intel.com/t"rget/t"rgetscript
min.#s$%uni&ue identi!er'"(</script(
"here {unique identifier} is indicated on the Intel XDK New Test
panel$
>$ .aunch the app on the device via App (review$
A$ 3lic) on the =egin Debugging on Device button in the Intel XDK New
Test panel$
2 - 1&
2013 Intel Corporation.
Figure 13 *dd t$e Escript@ )rom t$e Test ta0 onto all $tml pages t$at you
need to remotely de0ug(
Fast Track to Intel XDK New
As depicted in figure <H, after you clic) the egin !ebugging on !e"ice
button, the weinre e0tension for the 3hromium browser appears, enabling
you to troubleshoot your app as it7s runs on your device$ 'he debugger
functions nearly identically to the one that you used in the Cmulate panel$
In a manner similar to the 3hromium debugger, you can inspect the
browser7s D8-, review networ) traffic, review runtime errors, and even
interact directly with the app through the debugger7s 3onsole view$
2 - 1'
2013 Intel Corporation.
Figure 14 Invo%ing t$e "einre remote de0ugger(
Figure 18 Using t$e "einre remote de0ugger(
Getting tarte! wit" Intel XDK New
0al1throgh 222: Debgging ,or )pplications
In this lab, you will perform the following tas)s:
Use %avascript7s debuggerL and console$log12 methods to aid you in
your debugging efforts$
Use the 3hromium debugger to step through your code on an emulated
device$
Use the weinre debugger to step through code in your app running on a
physical device$
Steps
Open a -roject
<$ 8pen Intel XDK New
>$ 3lic) on the word PF9GECTS in the top5left corner of the +UI$
A$ 3lic) the 9pen a Project button$
B$ &elect the following file:
/!t)ntel*d+,ew/w"l+/w"l+-.-/w"l+-.-./d+
/$ 3lic) the open button$
)dd 5avaScript Debgging State&ents
F$ 3lic) on the Develop tab$
H$ In the pro9ect7s file browser, clic) on the inde?($tml file$
I$ 3lic) on the C9DE button$
D$ 8n line A>, insert the following statement to establish a programmatic
brea)point:
debugger;
<E$ After the code that you inserted from the prior step, insert a for loop
that loops from E to B:
!or (0"r i=1; i<2; i33) %
'
<<$ Inside the for loop, insert a statement that outputs the value of the
variable i to the debugging console:
console.log(i);
<>$ &elect File M Save from the code editor7s menu$
2 - 1(
2013 Intel Corporation.
Fast Track to Intel XDK New
Inspect the app in the +&lator
<A$ 3lic) on the Emulate tab
<B$ 3lic) on the De0ug button
</$ 3lic) on the De0ug /e button within the app running in the emulator$
'he sources panel of the debugger should activate$
<F$ 3lic) on the NOP button in the "atch C0pressions title bar$
<H$ Cnter i as the e0pression and press NCnterP
<I$ 3lic) the debugger7s &tep 8ver button to advance the program
e0ecution through the for loop$ Notice how the value for the variable I
changes in the "atch panel$
<D$ -ouse5over the variable i, located in the console$log12 statement$
!overing your mouse over the variable should display its value$
>E$ 8pen the &cope ?ariables panel and review the contents of the
variables that are present$
><$ 3lic) the Fesume Script E?ecution button to allow your scripts to run
to completion$
>>$ 3lic) on the debugger7s 3onsole tab$ *ou should see the results from
e0ecuting your console$log12 statement$
Use the 'e&ote Debgger
>A$ In the Intel XDK New, clic) on the Test tab$
>B$ &croll down the page to the 9n Device De0ugging section$
>/$ 3opy the script tag displayed at the bottom of the page to your
clipboard$
>F$ 3lic) on the Develop tab$
>H$ 8pen the inde?($tml file in Code view$
>I$ (aste the Escript@ tag 9ust above the E!$ead@ tag$
>D$ :rom the code editing menu bar, select File M Save(
AE$ 3lic) the Test tab$
A<$ 3lic) on the Pus$ Files button$
A>$ @un Intel *pp Previe" on your mobile device$
AA$ 'ap on the 3amera button and scan the G@ code from the Test tab$
AB$ 8n your mobile device, tap 96 to launch the app$
A/$ In the Intel XDK 'est tab, clic) on the Begin De0ugging on Device
button$
AF$ 3lic) on the hyperlin)ed target reference$
AH$ In the weinre debugger, clic) on the Console button$
AI$ In the app running on your mobile device, tap the De0ug /e button$
2 - 20
2013 Intel Corporation.
Getting tarte! wit" Intel XDK New
AD$ Note that the console output from your mobile app running on your
device appears in the weinre remote debugger console view$
BE$ 3lic) on the End De0ugging =utton to end your remote debugging
session$
H End o) 7al%t$roug$ &&
2 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
Getting !elp
Intel XDK New ships with online documentation and sample applications,
and has community support resources available as well$ As illustrated by
:igure <D, help features are available by clic)ing on the yellow ;uestion
mar) button$
Using the XDK Doc&entation
&electing the #isit the $elp Page lin) opens your web browser to the Intel
Developer Qone at http:JJsoftware$intel$comJen5usJhtml/JarticlesJ0d)docs$
:rom here, you can get ;uic) access to Intel7s App :ramewor) docs, the
Apache 3ordova A(I docs, 9Guery A(I, and +oogle 3hrome Dev 'ools
docs
2 - 22
2013 Intel Corporation.
Figure 1; *ccessing $elp resources(
Figure #B T$e Intel 5D6 -e" :elp Page
Getting tarte! wit" Intel XDK New
(erhaps the most relevant documentation for this course is the Intel XDK
A(I documentation, which contains information about available 9ava&cript
methods in the intel$0d) namespace$ *ou can access these resources
directly from:
http:JJwww$html/dev5software$intel$comJdocumentationJ9sA(IJinde0$html
'his pac)age documents methods that enable you to access the following
resources:
-obile device physical resources, including the camera and
accelerometer
:aceboo) A(I support
&upporting multitouch on Android devices
oAuth authentication methods
Interacting with the accelerated 3anvas App +ame interface plugin
2 - 23
2013 Intel Corporation.
Figure #1 Documation )or t$e intel(?d% javascript pac%age
Fast Track to Intel XDK New
Using the 6or&s
'he Intel XDK New developer forum, depicted in :igure >>, is a great
resource for interfacing with other developers and the Intel XDK
development team$ (ost your technical support ;uestions here and receive
;uic) responses from other developers as well as members of Intel7s XDK
New development team$
2 - 2#
2013 Intel Corporation.
Figure ## T$e Intel 5D6 -e" developer )orum(
Getting tarte! wit" Intel XDK New
'eviewing the Sa&ple )pplications
As depicted in :igure >A, Intel XDK New ships with <B separate sample
applications that aptly demonstrate how to use commonly re;uested mobile
app features$ Documentation for each e0ample, accessed by pressing the
document button, highlights the specific A(I calls that were critical in
producing the desired outcome$
'he e0amples include the following:
-ame Description
Folling Can 3aptures a deviceRs accelerometer data and animates an
!'-. element using 3&& transformations$
Flood PuIIle A simple pu66le game implemented as a Single Page
%pp that illustrates how to use %avascript to modify 3&&
styles based on user interactions$
Spring0oard A 9Guery5-obile based application that demonstrates
custom styling techni;ues which adapt to various screen
si6es and rotations, and achieve a different loo) and feel
than %G- defaults$
Buttons A basic e0ample of that reads the touchStart and
touchEnd %ava&cript events in order to provide a
responsive visual cue to the user that a button is being
pressed$
2 - 2$
2013 Intel Corporation.
Figure #' 9pening a sample application
Fast Track to Intel XDK New
-ame Description
*pp
Frame"or%
A simple app that demonstrates how to use various Intel
App :ramewor) UI components$
.eolocation (lots the user7s geolocation on a +oogle -ap, updating
every five seconds$
Ta0 -av A multi5page %G- scaffold using tab5based navigation$ It
demonstrates how to create a custom options menu
widget that maintains state across page transitions and
how to dynamically in9ect widgets into the D8-$
FP-
Calculator
A themable stac)5based calculator that uses different
color schemes, styles, and button animations$
Basic :y0rid
*pp
Demonstrates how to use the intel$0d) library to access
native device features$
:ello 7orld 'he classic$ *ou )now it, you love it$
P$one.ap
*udio
Uses a 3ordova media ob9ect to record and playbac)
audio$
To"ers o)
:anoi
Uses 3&& and 9Guery to animate solving the classic
'owers of !anoi# pu66le$
Counting
Beads
A simple !'-./5based game that teaches young
children how to count up to /E$
I>/ +ist
Vie"
A %G-5based app that uses the @otten 'omatoes A(I to
create a paginated list of D?D rentals$ It demonstrates
how to populate a list view with live data and
dynamically generate pages$
2 - 2%
2013 Intel Corporation.
Getting tarte! wit" Intel XDK New
0al1throgh 227: Using a Starter )pp
In this lab, you will perform the following tas)s:
@eview the 'ab Nav sample application
'he :riends with =eer application that you7re going to create uses a similar
navigational structure$ *ou7ll review and learn how to apply the techni;ues
used to create this app later in the course$
Steps
/reate a New -roject (ro& a Sa&ple
<$ 8pen Intel XDK New
>$ 3lic) on the word (ro9ects in the top left corner of the +UI$
A$ 3lic) the Start a -e" Project button$
B$ 3lic) on the 7or% "it$ a Demo tab$
/$ 3lic) on the I>/ Ta0 -av app$
F$ 3lic) -e?t$
H$ Cnter the following information:
Name your pro9ect: wal)>SA
(ro9ect .ocation: JpathJtoJftIntelXd)NewJwal)Jwal)>SA
I$ 3lic) the 3reate button$
D$ 3lic) -o T$an%s
<E$ 3lic) +et<s .o
'eview the )pp
<<$ 3lic) on the Emulate tab and review how the application runs on5
screen$ Note the tab5based navigation that7s doc)ed to the bottom of the
screen$
<>$ 3lic) on the Develop tab$
<A$ 3lic) on the inde?($tml file$
<B$ @eview the structure of the !'-.$ Note that each page is represented
by a set of logical pages, set off by a TdivM tag with data5roleU#page#$
</$ @eview the structure of the tab bar which manifests from the
Tdiv data5roleU#footer#M mar)up$
<F$ 8pen the file appJtabbedImages$9s and review the code$ Note that 9G-
pages fire an event named pageshow# when they appear to a user$
H End o) 7al%t$roug$ &&
2 - 2&
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit S&&ar,
Designing and developing applications for handheld devices is a
completely different process than writing for des)top browsers
Intel XDK New is an integrated development environment for creating
mobile applications built on web standards V !'-. /, %ava&cript, and
3&&A$
Intel XDK New integrates many best5of5breed !'-./ development
tools including the following:
-obi8ne "*&I"*+ visual interface designer
=rac)ets code editor
+oogle 3hromium Debugger
Apache @ipple Cmulator
Intel App (review mobile app launcher
weinre remote debugger
Apache 3ordova native app pac)ager
app-obi cloud services
*ou can develop your application using a variety of %avascript
framewor)s including 9Guery -obile, 'op3oat, =ootstrap, and Intel7s
App :ramewor)$
Intel7s App :ramewor) A(I e0tends Apache 3ordova features$
'he 3hromium debugger and weinre remote debugger provide you
powerful troubleshooting capabilities and optimi6ation tips$
Intel XDK New ships with over a do6en sample apps that demonstrate
fre;uently re;uested mobile application features$
2 - 2'
2013 Intel Corporation.
Getting tarte! wit" Intel XDK New
Unit 'eview
<$ Do you need to install any software other than Intel XDK New in order
to develop, test, build, and deploy a mobile appW
>$ "hat are some advantages to developing a mobile app using web
standards instead of using 8b9ective53 or %avaW
A$ "hich physical device features can you test with the CmulatorW
B$ *ou must develop mobile apps using Intel7s App :ramewor)
1trueJfalse2
/$ .ist two programmatic techni;ues for inspecting the contents of a
9avascript variable$
2 - 2(
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 3:
Page Layout
Unit Objectives
After completing this unit, you should be able to:
Define logical pages in your application
Use layout controls to position elements on a page
Implement your app's navigational controls
Enable animated transitions beteen pages
Add te!t and image content to your application
Unit Topics
Defining "ages
Adding #ontent
3 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Pages
$%uery mobile uses a combination of &'() tags and &'()* custom data
properties to implement a page+based architecture for layout, An &'()
file may contain either a single page idget, or multiple page idgets,
"ages are typically indicated by -div. tags ith a data+role property e/ual
to page, (ost $%uery (obile pages, therefore use the the folloing
structure:
<div data-role="page" id="page1">
<!-- fixed page header -->
<-- page body -->
<!-- fixed page footer -->
</div>
Note: The Intel XDK New visual wysiwyg designer does not support
defining multiple pages within a single .html file.
0ou'll typically define pages ith the folloing attributes:
Attribute Description
data+dom+cache Determines hether to 1eep the page in the
D2( hen the user navigates aay from it,
data+theme 3ets the theme that ill be used to render the
page,
In most transactional+based apps, you'll also need to rite an event handler
that e!ecutes hen a page is instantiated in the D2(, 'ypically your event
handler ill donload ,4325 data from a 6E3'+based ebservice or
static ,4325 file and use it to populate the contents of the page,
'he structure of your page creation event listener ill resemble the
folloing:
$("#page1").on("pagereate"! f"ntion( event! "i ) #
// page initiali$ation logi goe% here.
&)'
3 - 2
2013 Intel Corporation.
Page a!o"t
Adding New Pages in Intel D!
0ou can add ne pages to
your app by right7cmd+
clic1ing in the files panel as
indicated in figure 8,
As indicated by 9igure :, you''ll be prompted to select a mobile 4avascript
frameor1 for each ne ,html file that you add to your pro$ect,
3 - 3
2013 Intel Corporation.
Figure 1: Adding new files to your project
Figure 2: You must select a framework for each html file.
Fast Track to Intel XDK New
Defining Page "eade#s
'he page header typically displays a page title and can display up to to
buttons hich are aligned to the left and right of the title, respectively,
&eaders are usually placed in a fi!ed position at either the top or bottom of
a page,
'he title te!t is normally an &8 heading element but it's possible to use any
heading level ;&8+&<= to allo for semantic fle!ibility,
'he basic synta! for implementing a header or resembles the folloing:
<div data-role="page" id="page1">
<div data-role="header" data-po%ition="fixed">
<h1>(riend% )ith *eer</h1>
</div>
<-- page body goe% here -->
<div data-role="footer" data-po%ition="fixed">
<!-- footer goe% here -->
</div>
</div>
Adding $uttons to "eade#s
'he header container automatically sets the first child lin1 to the left button
slot and the second child lin1 in the right as depicted by the folloing
e!ample:
<div data-role="header">
<a href="#" data-ion="delete">+anel</a>
<h1>,dit +ontat</h1>
<a href="#" data-ion="he-">.ave</a>
</div>
0ou can also set button position by applying the ui-btn-right and ui-btn-left
style classes, 'his is particularly useful if you need to place a single button
on the right of a header as illustrated by the folloing e!ample:
<div data-role="header">
<h1>Edit Contact</h1>
<a id="btnSave"
data-icon="check"
la%%=""i-btn-right">Save</a>
</div>
3 - #
2013 Intel Corporation.
Page a!o"t
Adding $ac% $uttons
4/uery (obile ill
automatically add a bac1
button on a header if the
folloing conditions e!ist:
'he page must have the
data+add+bac1+btn>true
property,
Using the data+rel>bac1
property on an anchor,
'he data+rel>bac1 property
causes the default href action to
be ignored in favor of
mimic1ing the broser's bac1
button behavior, going bac1 one history entry,
<div data-role="page"
id="editForm"
data-add-ba--btn="tr"e">
<div data-role="header"
data-position="fied">
<a data-rel="ba-"
data-role="b"tton"
data-ion="ba-">*a-</a>
<h1>Edit Friend !nfo</h1>
<b"tton
id="btnSaveFriend"
data-icon="save"
class=""i-btn-right">Save</a>
</div>
</div>
3 - $
2013 Intel Corporation.
Figure : Automatic back button support
Fast Track to Intel XDK New
Defining Navigation $a#s wit& t&e Nav$a# widget
'he 5av?ar idget enables you to place a navigation bar containing up to
five buttons, ithin a header or footer by using the folloing synta!:
<div data-role="footer">
<div data-role="navbar">
<"l>
<li><a href="#">/bo"t</a></li>
<li><a href="#">+ontat%</a></li>
<li><a href="#">*eer%</a></li>
<li><a href="#">0rin-!</a></li>
</"l>
</div>
</div>
?uttons are automatically si@ed to occupy the available idth7height of
their container,
3 - %
2013 Intel Corporation.
Figure !: "mplementing a #a$ %ar
Page a!o"t
'etting t&e Default $utton 'tate
'o set an item to be active by default, add class=""i-btn-active" to
the corresponding anchor, Add a class of "i-state-persist to ma1e the
$%uery automatically restore the active state each time the page is shon,
9or instance, a nav bar on the inde!,html page should resemble the
folloing:
<div data-role="footer">
<div data-role="navbar">
<"l>
<li><a
href="index.ht1l"
la%%=""i-btn-ative "i-%tate-per%i%t"
>/bo"t</a>
</li>
<li><a href="contacts#html">Contacts</a></li>
<li><a href="beers#html">$eers</a></li>
<li><a href="drink#html">%rink&</a></li>
</"l>
</div>
</div>
Adding Page T#ansitions
Add the data-transition property to each anchor tag in order to apply
a transition animation hen a user taps on a navbar button,
<div data-role="footer">
<div data-role="navbar">
<"l>
<li><a
href="inde#html"
class=""i-btn-active "i-state-persist"
>'bo"t</a>
</li>
<li><a href="contacts#html"
data-tran%ition="%lide">Contacts</a></li>
<li><a href="beers#html"
data-tran%ition="fade">$eers</a></li>
<li><a href="drink#html"
data-tran%ition="none">%rink&</a></li>
</"l>
</div>
</div>
3upported transitions include the folloing:
fade
pop
flip
turn
flo
slidefade
slide
slideup
slidedon
none
3 - &
2013 Intel Corporation.
Fast Track to Intel XDK New
Defining Navigation $a#s wit& t&e $utton (#oup )idget
'he #ontrolAroup idget groups
buttons together so that they loo1
similar to a navigation component,
'he effect is generated by
applying a
data+role>controlgroup property
to a -div. tag that raps a series
of anchor+based buttons as
illustrated by the folloing code
snippet:
<div data-role="ontrolgro"p">
<a href="#" data-role="b"tton">+li- 2e!</a>
<a href="#" data-role="b"tton">3o! +li- 1e!</a>
<a href="#" data-role="b"tton">/l)ay% li- 1e!</a>
</div>
0ou can set the buttons to display hori@ontally by adding the data+
type>hori@ontal attribute to the controlgroup container as illustrated
belo:
<div data-role="ontrolgro"p" data-type="hori$ontal">
<a href="#" data-role="b"tton">+li- 2e!</a>
<a href="#" data-role="b"tton">3o! +li- 1e!</a>
<a href="#" data-role="b"tton">/l)ay% li- 1e!</a>
</div>
2ther configuration properties for the controlgroup idget include:
&roperty Description
data+corners ?oolean, 3ets hether to dra the controlgroup ith
rounded corners, Defaults to true,
data+mini ?oolean, #ontrols hether to display more compact
buttons that use less space, Defaults to false,
3 - '
2013 Intel Corporation.
Figure ': (ontrol )roup %uttons
Figure *: A hori+ontally aligned button group.
Page a!o"t
Defining $uttons
?uttons are coded ith standard &'() anchor and input elements, then
enhanced by $%uery (obile to ma1e them more attractive and useable on a
mobile device, 0ou'll typically use anchor lin1s to define navigation
buttons, reserving input or button elements for form submission,
As previously described, the basic synta! for defining a button is the
folloing:
<a href="index.ht1l" data-role="b"tton">4o1e</a>
0ou can add icons to buttons by applying the data+icon property to the
anchor tag as illustrated belo:
<a
href="index.ht1l"
data-role="b"tton"
data-ion="ho1e">4o1e</a>
'he complete set of bundled icons is illustrated in 9igure B:
Icons may be positioned at the top, left, bottom, or right of the button's te!t
by setting the data+iconpos property:
<a
href="index.ht1l"
data-role="b"tton"
data-ion="ho1e"
data-ion-po%="top">4o1e</a>
0ou can change the button's theme, causing it to display ith either a light
bac1ground and dar1 te!t or a dar1 bac1ground and light te!t by applying
the data+theme property:
<a
href="index.ht1l"
data-role="b"tton"
data-the1e="b"
>4o1e</a>
3 - (
2013 Intel Corporation.
Figure ,: j-uery .obile "cons
Fast Track to Intel XDK New
*#eating $utton (#oups wit& t&e )+'I)+( Designe#
As depicted in 9igure C, you can drag a controlgroup idget to the center
of a footer, and then style each button individually through the properties
panel,
Navigating $etween "T,L -iles
$%uery (obile automatically ''hi$ac1s standard lin1s and form
submissions, converting them into an A4AD re/uests,
Ehenever a lin1 is clic1ed or a form is submitted, that event is
automatically intercepted by the A4AD nav system, An A4AD re/uest
based on the href or form action is issued instead of reloading the page,
Ehile the frameor1 aits for the A4AD response, a loader overlay is
displayed,
Ehen the re/uested page loads, $%uery (obile parses the document for an
element ith the data+role>FpageF attribute and inserts that code into the
D2( of the original page, Any idgets in the incoming page are enhanced
to apply all the styles and behavior, 'he title of the incoming page is noted
and the home page is updated hen the ne page is transitioned into
vie,
NOT: The rest of the in!oming page is dis!arded so any s!ripts"
stylesheets or other information will not be in!luded.
3 - 10
2013 Intel Corporation.
Figure /: 0sing the controlgroup widget and styling buttons in the
1Y2"1Y) designer
Page a!o"t
)al%t&#oug& 3./: Designing Pages
In this lab, you ill perform the folloing tas1s:
Define your application pages
Implement a basic header and footer
Implement the app's basic navigational structure
'teps
Open a P#oject
8, 2pen Intel DDG 5e
:, #lic1 on the ord &3456(72 in the top+left corner of the AUI,
H, #lic1 the 4pen a &roject button,
I, 3elect the folloing file:
/ft5ntel6d-3e)/)al-/)al-781/)al-781.xd-
*, #lic1 the open button,
Design t&e Page -oote#
<, 2pen the inde8.html file in Design vie,
B, Drag a F44763 control from the #ontrols+)ayout panel and drop it
onto the design canvas,
C, Drag a %0774# )340& control from the #ontrols+9orm panel and
drop it onto the center of the footer,
J, #lic1 on the first button on the left in the control group,
3 - 11
2013 Intel Corporation.
Figure 9: During this lab: you;ll "mplement tab<style na$igation and create
placeholder pages.
Fast Track to Intel XDK New
8K, In the %utton 2ettings panel, configure the folloing properties:
)abel : &ome
'heme: ;b= dar1
Icon: home
Icon position: top
88, #lic1 on the button ad$acent to the &ome button and configure the
folloing properties:
)abel : 9riends
Icon: user
Icon position: top
8:, #lic1 on the button ad$acent to the 9riends button and configure the
folloing properties:
)abel : ?eers
Icon: heart
Icon position: top
8H, Drag an additional button from the #ontrols . 9orm panel and drop it
to the far right of the controlgroup in the footer,
8I, #onfigure the folloing properties:
)abel : Drin1L
Icon: video
Icon position: top
8*, Ao to #ode vie and add the folloing attributes to the &ome
button:
href : inde!,html
data+transition: slide
8<, Add the folloing attributes to the 9riends button:
href: friends,html
data+transition: slide
8B, Add the folloing attributes to the ?eers button:
href: beers,html
data+transition: slide
8C, Add the folloing attributes to the Drin1 button:
href: drin1,html
data+transition: fade
8J, 3ave the file,
3 - 12
2013 Intel Corporation.
Page a!o"t
:K, #lic1 on the 6mulate tab, 'he footer should appear similar to 9igure
8K ,
*#eate t&e *ontacts0 $ee#s0 and D#in%1 Place&olde#s
:8, 6eturn to De$elop mode,
::, In the 9iles panel, right7cmd+clic1 on inde!,html and select #ew File,
:H, Enter the folloing file name:
friend%.ht1l
:I, Ehen prompted, select the j-uery .obile frameor1 and clic1
2elect,
:*, 6eturn to the inde8.html file
:<, Enter (ode =iew
:B, #opy the contents of the entire page to your clipboard
:C, 6eturn to friends.html
:J, Enter (ode vie
HK, "aste the contents of your clipboard into the friends.html file,
H8, #ut the folloing code to your clipboard and paste it into the anchor
tag that points to contacts,html:
data-the1e="b"
H:, 6eturn to Design mode,
HH, #lic1 on the page header,
HI, In the &eader 3ettings panel, change the title to the folloing:
(riend%
H*, 3ave the file,
H<, 6epeat steps :8+H* for the folloing files, changing the page header
and footer as appropriate:
beers,html
drin1,html
HB, #lic1 the 6mulate tab,
3 - 13
2013 Intel Corporation.
Figure 1>: 7he completed page footer.
Fast Track to Intel XDK New
HC, #onfirm that you can navigate beteen the pages by clic1ing7tapping
on the footer's navigation bar,
? 6nd of 1alkthrough ?
3 - 1#
2013 Intel Corporation.
Page a!o"t
Adding *ontent
0ou'll typically implement the page content area as a -div. tag ith the
attribute data+role>FcontentF, placing it beteen the page header and
footer as illustrated belo:
<div data-role="page" id="page1">
<div data-role="header" data-position="fied">
<h1>Friends (ith $eer</h1>
</div>
<div data-role="ontent">
4ello 9orld
</div>
<div data-role="footer" data-position="fied">
<&-- footer goes here -->
</div>
</div>
As illustrated in 9igure 88, the Intel DDG New E0EIE0A designer
enables you to /uic1ly lay out your content into a series of columns and
ros by dragging and dropping the #olumn and 6o idgets onto the
design canvas,
5ote that as you drag idgets from the #ontrols pallette, valid drop targets
become highlighted ith a cyan colored bac1ground in the design canvas,
Ehen you hover over a valid drop target, its color changes to orange,
3 - 1$
2013 Intel Corporation.
Figure 11: Drag and dropping rows and columns into the content area
Fast Track to Intel XDK New
'he designer generates a series of styled -div. elements, as illustrated by
the folloing code snippet:
<div la%%=""page-ontent">
<div la%%="grid grid-pad "ro) "ib8ro)81 ro)-height-1"
data-"ib="layo"t/ro)">
<div la%%="ol "ib8ol8: ol-;8<-1="
data-"ib="layo"t/ol">
<div la%%=")idget-ontainer ontent-area vertial-ol">
<div la%%=")idget "ib8)87 d-1argin%"
data-"ib="1edia/text">
<div la%%=")idget-ontainer left-reeptale"/>
<div la%%=")idget-ontainer right-reeptale"/>
<div>
<p>+ol"1n 1</p>
</div>
</div>
<%pan la%%=""ib8%hi1"></%pan>
</div>
</div>
<div la%%="ol "ib8ol8> ol-;8<-1="
data-"ib="layo"t/ol">
<div la%%=")idget-ontainer ontent-area vertial-ol">
<div la%%=")idget "ib8)8: d-1argin%"
data-"ib="1edia/text">
<div la%%=")idget-ontainer left-reeptale" />
<div la%%=")idget-ontainer right-reeptale"/>
<div>
<p>+ol"1n =</p>
</div>
</div>
<%pan la%%=""ib8%hi1"/>
</div>
</div>
<%pan la%%=""ib8%hi1"></%pan>
</div>
<div la%%="grid grid-pad "ro) "ib8ro)8= ro)-height-="
data-"ib="layo"t/ro)">
<div la%%="ol "ib8ol8< ol-;81=-1="
data-"ib="layo"t/ol">
<div la%%=")idget-ontainer ontent-area vertial-ol">
<div la%%=")idget "ib8)8> d-1argin%"
data-"ib="1edia/text">
<div la%%=")idget-ontainer left-reeptale"/>
<div la%%=")idget-ontainer right-reeptale" />
<div>
<p>?hi% ro) %pan% both ol"1n%</p>
</div>
</div>
<%pan la%%=""ib8%hi1"></%pan>
</div>
</div>
<%pan la%%=""ib8%hi1"></%pan>
</div>
</div>
3 - 1%
2013 Intel Corporation.
Page a!o"t
Adding Te2t
As depicted in 9igure 8:, you can add te!t to page by dragging and
dropping the 'e!t idget from the #ontrols+(edia panel and dropping it
onto the design canvas,
'he 'e!t 3ettings panel enables you to perform the folloing functions:
6eplace the )orum ipsum placeholder te!t
3et the id property of the generated -div. element,
3et display and visibility properties
Define #33 3tyles for te!t and margins
#reate define media /ueries that apply styles based on screen
resolution ;covered in unit J=
3 - 1&
2013 Intel Corporation.
Figure 12: Adding te8t to an app page.
Fast Track to Intel XDK New
Applying Typog#ap&ic 'tyles
As illustrated in 9igure 8H, the
E03IE0A interface enables you to
define typographic styles for your page
elements, #onfigurable options include:
9ont 3i@e
9ont 3tyle
9ont Eeight
#olor
9ont 9amily
'e!t Decoration
'e!t Align
)ine &eight
3tyle classes that are defined for one element can be applied to other
elements in the E03IE0A designer,
0ou'll learn ho to e!tend these styling capabilities via #ode Mie in unit
J,
Adding I3ages
'he I(A idget enables you to add
$pg, png, or gif images to your
content, As depicted in 9igure 8I,
any images that have been placed in
your pro$ect's folder structure may be
selected from the drop+don list in
the I(A 3ettings panel, 0ou can also
configure Alt te!t ;to meet section
*KC accessibility re/uirements=, edit
a visible caption, and set the
generated elements D2( identifier,
3 - 1'
2013 Intel Corporation.
Figure 1: Defining typographic
styles
Figure 1!: (onfiguring an ".)
widget
Page a!o"t
)al%t&#oug& 3.4: Adding *ontent
In this lab, you ill perform the folloing
tas1s:
Add te!t content to the home page,
Define typographic styles,
Add an image to the home page,
'teps
Open a P#oject
8, 2pen Intel DDG 5e
:, #lic1 on the ord &3456(72 in the top+
left corner of the AUI,
H, #lic1 the 4pen a &roject button,
I, 3elect the folloing file:
/ft5ntel6d-3e)/)al-/)al-78=/)al-78=.xd-
*, #lic1 the open button,
Add Te2t
<, 9rom the (ontrols . .edia panel, drag a 7e8t idget and drop it onto
the design canvas, placing it beteen the header and footer,
B, 2pen walk@2AresourcesAhomepagete8t.t8t in #ode vie,
C, #opy the contents of the first paragraph of homepagete8t.t8t to your
clipboard,
J, 2pen inde8.html in Design vie,
8K, In the Design canvas, clic1 on the 7e8t idget,
88, In the 7e8t 2ettings panel, paste the contents of your clipboard into the
7e8t field,
Define Typog#ap&ic 'tyles
8:, In the 7e8t 2ettings panel, clic1 on the 7e8t button and select #ew...
8H, Enter a style class name of homepage
8I, Enter the folloing properties:
9ont+3i@e: >.9em
9ont+9amily: sans<serif
)ine+&eight: normal
3 - 1(
2013 Intel Corporation.
Figure 1': Your goal
Fast Track to Intel XDK New
Add an I3age
8*, 9rom the (ontrols . .edia panel, drag an ".) idget and drop it
underneath the 7e8t bloc1 on the Design #anvas,
8<, #onfigure the folloing I(A settings:
3rc: 3esourcesA%eer.jpg
Alt: %eer: 7he cause and solution to all of our problems
Add a 'econd Te2t )idget
8B, 9rom the (ontrols . .edia panel, drag a 7e8t idget and drop it onto
the design canvas, placing it directly underneath the image,
8C, 2pen walk@2AresourcesAhomepagete8t.t8t in #ode vie,
8J, 3tarting ith the second paragraph, copy the contents of
homepagete8t.t8t to your clipboard,
:K, 2pen inde8.html in Design vie,
:8, In the Design canvas, clic1 on the 7e8t idget,
::, In the 7e8t 2ettings panel, paste the contents of your clipboard into the
7e8t field,
Apply t&e &o3epagete2t Te2t 'tyle
:H, In the 7e8t 2ettings . 2tyles panel, clic1 on the 7e8t menu and select
homepagete8t as illustrated belo:
:I, 3ave the file
:*, #lic1 the 6mulate button, 0our app should appear similar to 9igure 8*
on the previous page,
N End of Eal1through ++
3 - 20
2013 Intel Corporation.
Page a!o"t
Unit 'u33a#y
$%uery mobile uses a combination of &'() tags and &'()* custom
data properties to implement a page+based architecture for layout,
$%uery mobile behaviors are typically defined by adding custom data
properties to html elements,
Ehen pages are created in the mobile broser's D2(, the
pagecreate event is fired,
Every html page in your app must be lin1ed to a mobile 4ava3cript
frameor1,
"age headers and footers can be doc1ed into a fi!ed position,
4%( can automatically add a bac1 button on a header,
Use the ?uttonAroup idget to easily add navigation to your apps,
4%( supports slide and fade transitions beteen pages,
?uttons may be styled ith icons and themes,
'he Intel DDG App Designer enables you to lay out your pages using a
ros7column metaphor,
3tyle classes that are defined for an element can be applied to other
elements ithin your app,
'he App Designer ill automatically locate all images that have been
placed ithin your pro$ect folder,
3 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit 5eview
8, "ages do not need to be lin1ed to a mobile $avascript frameor1
;true7false=
:, 0ou cannot define custom icons for your buttons ;true7false=
H, An &'() file may only contain a single page vie ;true7false=
I, 'he App Designer generates &'() table mar1up to ensure
compatibility ith the broadest range of brosers ;true7false=
*, &o can you impement a page transition animationO
3 - 22
2013 Intel Corporation.
Unit 4:
Working with Data
Unit Objectives
After completing this unit, you should be able to:
Use jQuery Mobile to make asynchronous data requests
Output structured data into a Listie!
"ransfer data read from an application ser#er into an $"ML% Local
&QL 'atabase
(ead data from the de#ice)s *ontacts list
Unit Topics
Making +,ternal 'ata (equests
-orking !ith the Listie!
*aching 'ata in a Local 'atabase
.mporting 'ata from the *ontacts List
4 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Making External Data Reqests
/query mobile supports making t!o different types of data requests from a
!eb bro!ser:
Use the 01aja,23 method to read and post e,ternal data using
/a#ascript)s nati#e 4ml$ttp(equest23 method1
Use the 01get/&O523 method to read structured data in /a#a&cript
Object 5otation format 2/&O53 from a remote domain by dynamically
injecting a 6script7 tag into your application)s 'OM1
Making !"!# Data Reqests $ro% "&M
8ou can make A/A4 requests to a ser#er using the 01aja,23 method
illustrated belo!1 01aja,23 should be used !hene#er you need to retrie#e
e,ternal data that)s not in /&O5 format or if you need to 9O&" data to a
ser#er1
$.ajax({
url: 'myservice.cfc?method=getdata',
type: 'G!',
data!ype: 'jso"',
error : fu"ctio" (#{ alert('there $as a" error'#% &,
success: fu"ctio" (data# {
co"sole.log(data#%
'' de(ugger%
&
&#%
5ote the follo!ing:
"he callback to the success or error handler is e,ecuted
asynchronously1
"he success handler recei#es the data as a ja#ascript object1 8ou do not
need to use the e#al23 method or an equi#alent to parse the /&O5 into a
nati#e /a#a&cript object1
Use the console1log23 method to output results to your debugger1
Alternately, you can use the debugger: command to set a programmatic
breakpoint1
-eb apps !ill not be able to make cross;domain requests unless the
remote host supports cross;origin resource sharing 2*O(&3
*ordo#a;based apps !ill need to !hitelist all e,ternal domains
2co#ered in unit <=31
4 - 2
2013 Intel Corporation.
Workin wit! Data
Making "'O() Reqests $ro% "&M
8ou can make cross;domain /&O5;9 requests from jQuery using the
0get/&O5 method illustrated belo!:
var url='http:''someurl'some)pp*erver*ervice.php?'%
$.get+*,-(url . 'method=somemethod/call(ac0=?',
fu"ctio"(data# {
co"sole.log(data#%
&
#%
5ote that the > Used in the callback url is replaced at runtime by a jQuery
!ith a randomly generated set of numbers1 /&O59 ?+" requests
therefore typically resemble the follo!ing:
Use 01get/&O523 !hene#er you need to retrie#e /&O5 data from a remote
domain that does not support *O(&1
4 - 3
2013 Intel Corporation.
Figure 1: A typical JSONP Request.
Fast Track to Intel XDK New
De$erring Data Reqests Until )age !ctivation
One of the challenges that you !ill ha#e !ith building larger, more
complicated /QM apps is minimi@ing the amount of memory that your app
consumes1 One strategy for managing memory is to not load data until it is
absolutely needed1 Aor instance, if a data request is required to populate a
list #ie!, you might !ant to defer making the request until such time as the
page is requested by the user1
"he typical pattern to trigger the e,ecution of code on page #isibility is the
follo!ing:
$(docume"t#.(i"d('pagei"it', fu"ctio"(# {
$(docume"t#.o"( 1pagecha"ge1, fu"ctio"(eve"t,page# {
s$itch(page.to2age345.id# {
case 'page6' :
'' i"itiali7e page 6
(rea0%
case 'page8' :
'' i"itiali7e page 8
(rea0%
&%
&#%
&#%
.n the preceding code snippet, the pageinit e#ent is triggered once the
inde,1html page has completed loading in the bro!ser1 .n jQuery Mobile,
listening for pageinit e#ent should be used in lieu of document1onready231
"he pagechange e#ent is triggered !hene#er an anchor tag is acti#ated by
a user, causing jQM to intercept the request and load the requested html
page1 8ou can parse the second argument returned to the pagechange e#ent
handler to determine the id property contained !ithin the di# tag
containing the data;roleBCpageC attribute as illustrated belo!:
9div class=1upage1 data:role=1page1 id=1page61;
4 - 4
2013 Intel Corporation.
Workin wit! Data
Developing "avascript *lasses to Encapslate Event +an,lers
As your application gro!s in si@e, you may find it useful to bundle all of a
page)s e#ent listeners into a single /a#ascript object1 "his approach has
se#eral benefits:
+ncapsulation
9rotected #ariable scoping
*ode (euse
"he general approach to implement this coding style is to define a global
ja#ascript object in your inde,1html file for each DpageC of your app1 Aor
e,ample, you might define a /a#ascript object container for your beers;
page related subroutines as illustrated by the follo!ing:
var <eers2age = {
&%
.nside of the /a#a&cript object, you)ll place all of the page)s dynamic
properties and methods:
var BeersPage = {
i"itiali7ed: false,
i"it: fu"ctio"(# {
this.i"itiali7ed = true%
&
}
5ote that in the preceding case, the init23 method refers to the initialized
#ariable using the this scope as both the init() method and the initialized
property are both members of the same object1
8ou could then in#oke the init23 method for beersPage through the
follo!ing synta,:
<eers2age.i"it(#%
8ou !ill use this de#elopment methodology throughout this course1
4 - "
2013 Intel Corporation.
Fast Track to Intel XDK New
*aching Data -n a .ocal /ariable
Arom a performance perspecti#e, $""9 transactions from mobile de#ices
are #ery costly1 8ou can reduce e,ternal calls by caching data in memory,
html% local storage, or html% local database1
.t)s relati#ely straightfor!ard to e,tend our class system in order to persist
remote data in a local #ariable1 .n the follo!ing code, !e)#e e,tended the
Eeers class described on the prior page by adding an additional property
named data1 Once the /&O5;9 data has been successfully read from the
ser#er, it)s placed into the data property !here it can be referred for the
duration that the app remains running1 A strategically placed if23 condition
pre#ents the remote data from being fetched more than once1
var Beers = {
initialized: false,
data : "ull,
init: function() {
var me = this% '' use closure to retai" scope
if (me.data === "ull // =me.i"itiali7ed# {
me.i"itiali7ed = true%
var url= "http://xdtraining!co"/ftxdne#/data/$eer!cfc"%
&!get'()*(url + ","ethod=getBeer-ist.call$ac=,",
function(data) {
me.data = data%
}
)%
}
}
}
4 - #
2013 Intel Corporation.
Workin wit! Data
Walkthrogh 401: Making External Data Reqests
.n this !alkthrough, you !ill start de#eloping the DEeer ListC feature of the
application1
Make a local data request to retrie#e a list of Eeers that)s encoded in
/&O5 format1
'isplay the results from the transaction in the debugger1
'teps
Open the )roject
<1 Open .ntel 4'F 5e!
G1 *lick on the !ord PROJECTS in the top;left corner of the ?U.1
H1 *lick the Open a Proect button1
I1 &elect the follo!ing file:
'ft>"tel?d0-e$'$al0'$al0@A6'$al0@A6.xd0
De$ine a pageinit Event .istener
%1 Open the follo!ing U(L and re#ie! the output:
http://xdtraining!co"/ftxdne#/data/$eer!cfc,
"ethod=getBeer-ist
J1 Open the inde,1html file in *ode #ie!1
K1 .mmediately prior to the closing 6head7 tag, insert a /a#ascript block:
9script type=Btext'javascriptB;
9'script;
L1 .nside the 6script7, listen for the pageinit e#ent to be triggered by the
inde, page:
8our code should appear similar to the follo!ing:
/script t0pe="text/1avascript"2
$(docume"t#.(i"d('pagei"it', fu"ctio"(# {
&#%
//script2
4 - $
2013 Intel Corporation.
Fast Track to Intel XDK New
M1 .nside the e#ent handler function, define a #ariable named page that
retrie#es the file name of the current url1 8our code should resemble
the follo!ing:
var page = eve"t.target.(aseCD>.split('''#%
page = page3page.le"gth : 65%
<=1 After the code that you inserted from the prior step, check for the
e,istence of the global #ariable App1initiali@ed1 .f the #ariable has bot
been defined, set it equal to true and call a method named App1init23
!hich you !ill define later in this e,ercise1
&(docu"ent)!$ind(3pageinit3, function(event,o$1) {
var page = event!target!$ase456!split(3/3)%
page = page7page!length 8 9:%
if (=)pp.i"itiali7ed# {
)pp.i"itiali7ed = true%
)pp.i"it(#%
&
}
<<1 After the code that you inserted from the prior step, insert a s!itchNcase
statement that e#aluates the contents of the page #ariable and checks it
against each of your application)s pages1
s$itch (page# {
case 'i"dex.html' :
(rea0%
case '(eers.html' :
(rea0%
case 'frie"ds.html' :
(rea0%
case 'dri"0.html' :
(rea0%
&
*reate the !pp *lass an, 2et the Data
<G1 -here indicated by the comment, define an object named App !ith
the follo!ing properties:
initiali@ed: false
beers: null
<H1 erify that your code appears as follo!s:
var )pp = {
i"itiali7ed: false,
(eers: "ull
&
4 - %
2013 Intel Corporation.
Workin wit! Data
Retrieve an, *ache the Data
<I1 'efine t!o method for the App object named init23 and cacheEeers231
var ;pp = {
initialized: false,
$eers: null,
i"it: fu"ctio"(# {
&,
cache<eers: fu"ctio"(# {
&
}
<%1 .n#oke the cacheEeers23 method from the init23 method as illustrated
belo!:
var ;pp = {
initialized: false,
$eers: null,
init: function() {
this.cache<eers(#%
},
cacheBeers: function() {
}
}
Make a "'O(0) Reqest
<J1 .nside the cacheEeers method, define a local #ariable named !e that
points to the "eers class and set the initiali#e$ property to true1
var me = this%
<K1 .mmediately after the code that you inserted from the prior step, make
a /&O5;9 request to the follo!ing U(L, placing the result in the Eeers
class data property and dumping its results to the debugging console1
http:''xd0trai"i"g.com'ftxd0"e$'data'(eer.cfc?
method=get<eerEist/call(ac0=?
<L1 erify that your code appears similar to the follo!ing:
cacheBeers: function() {
var "e = this%
var url = "http://xdtraining!co"/ftxdne#/data/$eer!cfc"%
$.get+*,-(url . 1?method=get<eerEist/call(ac0=?1,
fu"ctio"(data# {
me.(eers = data%
co"sole.log(data#%
&
#%
}
<M1 &a#e the file1
4 - &
2013 Intel Corporation.
Fast Track to Intel XDK New
G=1 *lick on the E!ulate tab1
G<1 Open the debugger1 8ou should see the array output from the data
request as illustrated in Aigure G:
GG1 "ype the follo!ing code in the debugger)s console #ie! to output the
list of Eeers:
)pp.(eers
%%En$ o& 'al(through%%
4 - 10
2013 Intel Corporation.
Figure ): *nspecting the results o& the JSON%P request.
Workin wit! Data
Working with the .ist/iew
Use the Listie! !idget, depicted in Aigure H, to display the contents of
either unordered or ordered lists1
Add a data;roleBClist#ie!C property to a
6ul7 or 6ol7 entity in order to instantiate
a Listie!:
9ul data:role=1listvie$1;
9li;9hF;)aro"9'hF;9'li;
9li;9hF;)dam9'hF;9'li;
9li;9hF;)lexa"der9'hF;9'li;
9'ul;
2roping .ists
8ou can create grouped lists as illustrated in Aigure I by applying the
data;autodi#idersBOtrueO property to the 6ul7 entity as illustrated belo!1
5ote the follo!ing:
?rouped items must be placed in alphabetical order1
Ey default, the group name !ill be the uppercased first character of the
item)s te,t1
9ul
data:role=1listvie$1
data:autodividers=1true1;
9li;9hF;Gruc0er, )ida"9'hF;9'li;
9li;9hF;Gruc0er, Gyla"9'hF;9'li;
9li;9hF;Gruc0er, *teve9'hF;9'li;
9li;9hF;Galleri77o, Gavid9'hF;
9'li;
9'ul;
4 - 11
2013 Intel Corporation.
Figure +: A si!ple list,ie-
Figure .: /sing auto$i,i$ers
Fast Track to Intel XDK New
De$ining *sto% 2rop (a%es
"he follo!ing code snippets illustrate
ho! to define custom group names by
completing the follo!ing steps:
Add a custom data attribute to your
6li7 entities that define the group
name1
'efine an auto$i,i$ersSelector
method that dynamically returns the
group name based on list item
properties1
9rogrammatically refresh the list
Markup:
9ul data:role=1listvie$1 id=1perso"sEist1;
9li data:last"ame=1Gruc0er1;9hF;Gruc0er, )ida"9'hF;9'li;
9li data:last"ame=1Gruc0er1;9hF;Gruc0er, Gyla"9'hF;9'li;
9li data:last"ame=1Gruc0er1;9hF;Gruc0er, *teve9'hF;9'li;
9li data:last"ame=1Hatts1;9hF;Hatts, Gavid9'hF;9'li;
9li data:last"ame=1Hatts1;9hF;Hatts, !i(erius9'hF;9'li;
9'ul;
&cript:
$(1Iperso"sEist1#.listvie$({
autodividers: true,
autodividers*elector: fu"ctio"(li# {
retur" li.attr(1data:last"ame1#%
&
&#%
$(1Iperso"sEist1#.listvie$(1refresh1#%
D3na%icall3 )oplating a .ist $ro% "'O(
.n most use cases you)ll need to dynamically construct a list from data that
!as returned from an A/A4 or /&O5;9 call1 .n order to pull this off, you)ll
usually need to perform the follo!ing tasks:
'ynamically sort the array returned from the A/A4N/&O5;9 call1
*onstruct a template for generating list item markup1
?enerating html markup for each item and append to the Listie!1
(efresh the Listie!1
4 - 12
2013 Intel Corporation.
Figure 0: 1e&ining custo! group
na!es
Workin wit! Data
D3na%icall3 'orting an !rra3
Use /a#ascript)s array1sort23 method to sort an array of objects so that it
may be grouped correctly into a list1
9assing a function as an argument to the sort23 method enables you to sort
based on t!o or more fields P typically the field that you)re grouping on,
and the label for each list item1 .n this conte,t, /a#ascript automatically
passes in t!o objects to your custom function1 "he function, in turn, must
return the follo!ing:
;< if a 6 b
= if a BB b
< if b 7 a
"he follo!ing code snippet illustrates an ascending alphabetical sort for a
group;based sort1
data.sort(fu"ctio"(a,(# {
if(a.groupfield == (.groupfield# {
retur" (a.la(el 9 (.la(el# ? :6 :(a.la(el ; (.la(el# ? 6:4%
& else {
retur" (a.groupfield 9 (.groupfield# ? :6 : 6%
&
&#%
*onstrcting a Te%plate
Using templates impro#es code readability !hile reducing synta, errors
that ine#itably result from performing comple, multi;#ariable string
concatenation !ith the DQC operator1
-hile, jQuery <1, no longer supports built;in template methods, but you
can easily add a substitute by e,tending /a#a&cript)s &tring class as
illustrated by the follo!ing snippet:
*tri"g.prototype.format = fu"ctio" (# {
var args = argume"ts%
retur" this.replace(
'J{(Jd.#J&'g,
fu"ctio" (m, "# { retur" args3"5% &
#%
&%
"his &tring1format23 method enables you to easily perform dynamic string
replacement of placeholders through the follo!ing in#ocation:
var template = 1!he rai" i" {4& falls mostly o" the {6&1%
template.format(1*pai"1,1plai"1#%
'' output: !he rai" i" *pai" falls mostly o" the plai"
4 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
D3na%icall3 2enerating .ist -te%s
"he problem !ith using the aforementioned synta,, ho!e#er, is that
creating a multi;line DtemplateC remains some!hat error;prone since you
can)t insert line breaks !ithin a /a#ascript string1 &haring the template
across multiple applications !ould also be problematic1
"he solution is to break the template out into a separate script as illustrated
belo!:
9script type=1text'template1 id=1tplEist>tem1;
9li data:value=1{4&1;
9hF;{6&9'hF;
9'li;
9'script;
8ou can then con#ert the contents of the script to an $"ML string using
jQuery)s html23 method:
var item!emplate = $(1ItplEist>tem1#.html(#%
5o! that you)#e got your template in place, you can easily loop through
your dataset, appending markup to your list1 5ote that once you ha#e
completed adding list items, you must programmatically refresh the list as
illustrated by the follo!ing e,ample:
var list = $('ulIperso"sEist'#%
list.empty(#% '' remove all items
for (var i=4% i9 data.le"gth% i..# {
var item = data3i5%
var str = item!emplate.format(item.id, item."ame#%
list.appe"d(str#%
&
'' redra$ the list K a(solutely DLC>DG===
list.listvie$(1refresh1#%
4 - 14
2013 Intel Corporation.
Workin wit! Data
!,,ing a 'earch 4ilter
Adding the data;filterBOtrueO property
to a list causes the jQuery Mobile
frame!ork to prepend a search bo, that
filters out list items that don)t contain
the te,t that the user types into the bo,1
"he input)s placeholder te,t defaults to
OAilter items111O
/ul
data8role="listvie#"
id="persons-ist"
data:filter=1true1 2
/li data8lastna"e="<rucer"2/h=2<rucer, ;idan//h=2//li2
/li data8lastna"e="<rucer"2/h=2<rucer, <0lan//h=2//li2
/li data8lastna"e="<rucer"2/h=2<rucer, (teve//h=2//li2
/li data8lastna"e=">atts"2/h=2>atts, <avid//h=2//li2
/li data8lastna"e=">atts"2/h=2>atts, ?i$erius//h=2//li2
//ul2
Displa3ing *onts an, *arats in a .ist
"he frame!ork includes te,t formatting
con#entions for common list patterns like
headerNdescriptions, secondary
information and counts through semantic
$"ML markup1
"o add a count indicator to the right
of the list item, !rap the number in an
element !ith a class of ui8li8count
"o add a carat indicator, insert the follo!ing into each list item:
9spa"
class=1ui:ico" ui:ico":arro$:r ui:ico":shado$1;/"(sp%9'spa";
.istening $or a Tap Event
Listen for tap e#ents on list items by using the bind23 method as illustrated
belo!:
$('Iperso"sEist ; li'#.(i"d('tap', fu"ctio"(e# {
var targetMalue = this.get)ttri(ute('data:last"ame'#%
alert(1Nou selected the 1 . targetMalue . 1 family1#%
&#%
4 - 1"
2013 Intel Corporation.
Figure 2: A$$ing a Search Filter
Fast Track to Intel XDK New
Walkthrogh 405: D3na%icall3
2enerating .ists
.n this !alkthrough, you !ill enhance your
application by outputting the data that you
retrie#ed in the pre#ious !alkthrough into a
Listie!1
?enerate a list #ie!
&ort an array of records
Output records into a grouped list
'teps
Open the )roject
<1 Open .ntel 4'F 5e!
G1 *lick on the !ord PROJECTS in the
top;left corner of the ?U.1
H1 *lick the Open a Proect button1
I1 &elect the follo!ing file:
/ft6ntel@d*e#/#al/#alABC/#alABC!xd
'ort the Dataset
%1 -here indicated by the comment, sort the dataset1
?roup on the country field
&ort by the name field
J1 8our code should appear similar to the follo!ing:
data.sort(fu"ctio"(a,(# {
if(a.cou"try == (.cou"try# {
retur" (a."ame 9 (."ame# ? :6 : (a."ame ; (."ame# ? 6 : 4%
& else {
retur" (a.cou"try 9 (.cou"try# ? :6 : 6%
&
&#%
K1 &a#e the file and run the app in the emulator1
L1 Open the debugger)s console #ie!1
M1 .nspect the results from the console1log231 8ou should see that the data
retrie#ed from the get/&O523 method has been sorted by country name
and beer name1
<=1 *lick on the 1e,elop tab1
4 - 1#
2013 Intel Corporation.
Figure 3: Output a list o&
"eers4 groupe$ 5y country o&
origin.
Workin wit! Data
*reate the .ist
<<1 Open the Eeers1html file in 'esign mode1
<G1 Arom the *ontrols 7 -idgets panel, drag a Listie! !idget and drop it
onto the design can#as bet!een the page)s header and footer1
<H1 .n the Listie! &ettings panel, turn on the follo!ing checkbo,es:
Ailter
Auto 'i#iders
id
<I1 +nter the follo!ing id for the Listie!:
(eerslist
<%1 &a#e the file and test the application in the emulator1 "he list should
appear1
De$ine a .ist -te% Te%plate
<J1 -here indicated by the comment, define a template for the list items
that you need to dynamically instantiate1 Assign an id property to the
template of DtplEeer.temC "he output from the template needs to
contain markup similar to the follo!ing:
9li data:value=161 cou"try=1C"ited *tates1;
9hF;*amuel )dams <osto" Eager9'hF;
9spa" class=1ui:li:cou"t1;49'spa";
9'li;
<K1 erify that your code appears similar to the follo!ing:
9script type=1text'template1 id=1tpl<eer>tem1;
9li data:value=1{4&1 cou"try=1{6&1;
9hF;{8&9'hF;
9spa" class=1ui:li:cou"t1;{F&9'spa";
9'li;
9'script;
)oplate the .ist
<L1 (eturn to 'e#elop mode1
<M1 Open inde,1html in *ode #ie!1
G=1 .nside the populateList23 method, define a #ariable named list that
points to the Listie! component1
var list = $('I(eerslist ; ul'#%
G<1 *lear the default list items from the list1 8our code should appear
similar to the follo!ing:
list.empty(#%
GG1 After the code that you inserted from the prior step, define a #ariable
named beer"emplate that points to the html in the tplEeer.tem element1
var (eer!emplate = $(1Itpl<eer>tem1#.html(#%
4 - 1$
2013 Intel Corporation.
Fast Track to Intel XDK New
GH1 After the code that you inserted from the prior step, loop through the
data retrie#ed from the /&O5;9 transaction1 8our code should appear
similar to the follo!ing:
for (var i=4% i9)pp.(eers.le"gth% i..# {
var item = )pp.(eers3i5%
&
GI1 .nside the for;loop, use the &tring1format23 method to generate a
dynamic list item and then append the result to the list1
for (var i=D% i/;pp!$eers!length% i++) {
var ite" = ;pp!$eers7i:%
list.appe"d((eer!emplate.format(
item.id, item.cou"try, item."ame, 4##%
}
G%1 After the for;loop, insert code to refresh the list1
list.listvie$(1refresh1#%
GJ1 &a#e the file and test the application in the emulator1 8ou !ill need to
test the app by launching the inde,1html file and then clicking on the
Eeers button in the footer1 5ote that the di#iders are not displaying
correctly1
*on$igre *sto% !toDivi,ers
GK1 (eturn to 'e#elop mode1
GL1 Open inde,1html in code #ie!1
GM1 .n the populateList23 method, immediately after the #ariable
declaration of the #ariable list , define a custom autodi#ider selector
that is generated from the #alue of the country attribute from each list
item1 8our code should appear similar to the follo!ing:
list.listvie$({
autodividers: true,
autodividers*elector: fu"ctio" ( li # {
retur" li.attr('cou"try'#%
&
&#%
H=1 &a#e the file and re;test in the emulator1 8our list di#iders should no!
contain the names of the countries from !here the beers !ere made1
6 En$ o& 'al(through %%
4 - 1%
2013 Intel Corporation.
Workin wit! Data
*aching Data in a .ocal Database
"he $"ML % specification defines database;agnostic &QL for accessing
local databases1 Most mobile bro!sers ha#e implemented &qlLite, enabling
you to use define database tables to store and retrie#e structured data1
"he amount of space allocated for local databases is configurable through
the bro!ser1 8ou can allocate up to %ME per app !ithout needing to
prompt the user to allocate more space1
*reating 6 Opening a .ocal Database
"he follo!ing access methods are supported for opening a database
connection:
7etho$ 1escription
!indo!1open'atabase23 *reates N opens a local database
-orkerUtils1open'atabase23 *reates N opens a local database using
!eb !orkers 2threads3
-orkerUtils1open'atabase&ync23 &ynchroni@es database information
+ach of the aforementioned methods require the follo!ing arguments
2listed in order31 .tems in bold are required:
Type 1escription
string 'atabase name1 -ill create ne!, empty database if the
specified name does not e,ist1
string 'atabase #ersion1
string 'isplay name
long +stimated si@e in bytes of the database si@e
&unction A callback to be in#oked if the database has not yet
been created1 "he callback function, in turn, must
in#oke the changeersion23 function to set the #ersion
id for the database1 .f a callback is not specified, the
database !ill be created and #ersion set to the #alue
specified by the second argument1 5ote that
changeersion23 is not implemented in all bro!sers1
4 - 1&
2013 Intel Corporation.
Fast Track to Intel XDK New
"he follo!ing e,ample illustrates the creation of a local database
containing a single table:
9script;
Oart = {
d( : "ull,
d(,pe" : fu"ctio"(# {
this.d( = ope"Gata(ase('cart',
'6.4',
'Oafe !o$"se"d *hoppi"g Oart',
PQ648@Q648@
#%
this.d(.tra"sactio"(fu"ctio"(tx# {
tx.execute*Rl('OD)! !)<E >S -,! ?>*!* cart(id
>-!GD 2D>T)DN UN )*O, desc !?!, Rty >-!, u"itprice -CT#',
35, this.o"*uccess, this.o"rror#%
&#%
&,
o"rror : fu"ctio"(tx, e# {alert(1rror: 1 . e.message#%&
o"*uccess : fu"ctio"(e# {alert(1*uccess1#% &
&
9'script;
9(ody o"load=1Oart.d(,pe"(#1;
)er$or%ing Database Transactions
8ou can perform database transactions using the transaction23 method of
your !eb database to define a transaction and then using the e,ecute&ql23
method of a transaction to process your queries1
"he e,ecute&ql23 method accepts four arguments, listed in order:
Arg 1escription
< "he &QL that you !ish to e,ecute
G Optional bind parameters
H Optional success handler function
I Optional error handler function
4 - 20
2013 Intel Corporation.
Workin wit! Data
"he follo!ing e,ample illustrates using a combination of hardcoded and
bind parameters, represented by question marks, to insert data into the cart
table:
Oart.d(.tra"sactio"(fu"ctio"(tx# {
var desc = 1Doasted !omato *oup1%
var Rty = 1P1%
var u"itprice = 1@.P1%
tx.execute*Rl('>-*D! >-!, cart (id, desc, Rty, u"itprice#
M)EC* (6,?,?,?#',
3desc,Rty,u"itprice5,
fu"ctio"(# {alert('success'#&,
fu"ctio"(# {alert('failed'#&#%
&#%
&imilarly, an update statement might resemble the follo!ing:
Oart.d(.tra"sactio"(fu"ctio"(tx# {
var desc = 1*tea01%
tx.execute*Rl('update cart set Rty = Rty . 6
$here desc = ?', 3desc5#%
&#%
'elete statements may be handled in a similar fashion:
Oart.d(.tra"sactio"(fu"ctio"(tx# {
var id = 6
tx.execute*Rl('delete from cart $here id= ?', 3id5#%
&#%
Retrieving Data $ro% the Database
"he e,ecute&ql23 method passes a &QL(esult&et object into its success
callback function1
&QL(esult&et has the follo!ing read;only attributes:
Attri5ute 1escription
insert.d (eturns the ro! .' of the data inserted into
the database
ro!sAffected "he number of ro!s affected by the operation
ro!s A &QL(esult&et(o!List object1 representing
the ro!s returned, in the order returned by the
database1 .f no ro!s !ere returned, it !ill be
empty 2@ero;length31
4 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
"he &QL(esult&et(o!List object contains a readonly attribute ; length P
!hich contains the number of ro!s returned1 .t also contains a getter
method named item231 9assing a ro! number to the item23 method returns a
structure representing the ro!)s column data1
"he follo!ing e,ample illustrates the process of retrie#ing and looping
through a &QL(esult&et(o!List object:
fu"ctio" getGata(d(# {
d(.tra"sactio"(fu"ctio"(tx# {
tx.execute*Rl(
'*EO! Q SD,T cart',
35,
fu"ctio" (tx, results# {
var le" = results.ro$s.le"gth%
for (var i = 4% i 9 le"% i..#
{
alert(results.ro$s.item(i#.desc#%
&
&#%
&#
&
+an,ling Database Errors
-hen an error occurs, either a &QL+rror or a &QL+,ception object is
passed to your handler1 Eoth objects ha#e similar structures, containing the
follo!ing attributes:
Attri5ute 1escription
code A numeric error code, described belo!
message A string containing the error message, locali@ed to
the user)s language
"he follo!ing error codes may be returned:
Constant Co$e 1escription
U5F5O-5R+(( = "ransaction failed for reasons not related
to the database1
'A"AEA&+R+(( < Operation failed due to the database, but
not co#ered by the other error types
+(&.O5R+(( G Operation failed because the database
#ersion did not match !ith the e,pected
#ersion
4 - 22
2013 Intel Corporation.
Workin wit! Data
Constant Co$e 1escription
"OORLA(?+R+(( H "he dataset returned from the database
!as too large
QUO"AR+(( I 5ot enough disk space allocated
&85"A4R+(( % Aailed due to a synta, error, or a
mismatch on the number of bind
parameters1
*O5"(A.5"R+(( J Aailed due to a referential integrity
constraint1
".M+OU"R+(( K *ould not establish a transaction lock in a
reasonable amount of time
"he follo!ing code snippet illustrates handling a database e,ception:
d(.tra"sactio"(fu"ctio"(tx# {
var desc = 1Doasted !omato *oup1%
var Rty = 1P1%
var u"itprice = 1@.P1%
tx.execute*Rl(
''.co"cat('>-*D! >-!, cart (id, desc, Rty, u"itprice#',
' M)EC* (6,?,?,?#'
#,
3desc,Rty,u"itprice5,
fu"ctio"(# {
alert('success'#%
&,
fu"ctio"(tx,e# {
alert('rror code: ' . e.code . ':' . e.message#%
&
#%
&#%
4 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
Manall3 /eri$3ing Database Transactions
8ou can manually #alidate that your data has been manipulated in the local
database by opening the *hromium debugger, clicking on the (esources
tab, and inspecting the contents of the -eb &QL assets as indicated in
figure L1
4 - 24
2013 Intel Corporation.
Figure 8: Re,ie-ing the contents o& a 'e5S9: ta5le.
Workin wit! Data
Walkthrogh 407: Working with
Web'&.
.n this !alkthrough, you !ill refactor your
application by caching the list of beers that
you retrie#ed in the pre#ious !alkthrough
into a !eb&QL database1
?enerate a -eb&QL database
(e#ie! code that inserts, updates, and
deletes from a -eb&QL 'atabase
&elect data from a -eb&QL table and
output it to a Listie!
'teps
Open the )roject
<1 Open .ntel 4'F 5e!
G1 *lick on the !ord PROJECTS in the
top;left corner of the ?U.1
H1 *lick the Open a Proect button1
I1 &elect the follo!ing file:
/ft6ntel@d*e#/#al/#alAB=/#alAB=!xd
Review the Web'&. Database !)-
%1 Open -al(.%+;s;local$5.s1 (e#ie! the code1 "his /a#a&cript class
defines a singleton that !ill handle all basic &QL operations !ithin
your application1 5ote that this library could be easily repurposed for
use in other applications1
"he init<= method defines t!o local database tables ; DbeerC !hich
!ill hold a cached list of beers and DfriendC !hich !ill store
e,tended contact information for your friends1
"he run9uery<= method e,ecutes the structured query language
2&QL3 code that you pass into it, passing the results to a callback
function1
"he -riteRecor$<= method performs insert and update operations
on the specified table1
"he i!portTa5le<= method copies an array of objects into the
specified database table1
4 - 2"
2013 Intel Corporation.
Figure >: Store4 retrie,e4 an$
output $ata &ro! a local
$ata5ase
Fast Track to Intel XDK New
*ache ,ata in Web'&.
J1 Open !alkI;HNinde,1html in *ode ie!
K1 .nside the get/&O5 callback function, in#oke the
Ariends-ithEeer'E1import"able23 method to transfer the json data
into the DEeerC table1
var ;pp = {
cacheBeers : function() {
var url = "http://xdtraining!co"/ftxdne#/data/$eer!cfc"%
&!get'()*(url + ","ethod=getBeer-ist.call$ac=,",
function(data) {
Srie"dsHith<eerG<.import!a(le('(eer',data#%
}
)%
}
}%
L1 &a#e the file1
M1 Open the emulator1
<=1 Open the debugger and click on the Resources panel1
<<1 Open -eb &QL 7 Ariends !ith Eeer1
<G1 *lick on the Eeer table1 8ou should see data in the panel1
Retrieve Data $ro% Web'&. an, Otpt to a .ist/iew
<H1 (eturn to the in$e?.ht!l in *ode #ie!1
<I1 (e#ie! the refactored "eers class1
<%1 -here indicated by the comment, call the
Frien$s'ith"eer1".run9uery<= method to e,ecute the &QL
statement defined on the pre#ious line1 8our code should appear
similar to the follo!ing:
Srie"dsHith<eerG<.ru"Luery(sRl, fu"ctio"(records# {
&#%
<J1 .nside the &QL callback function, loop through the data returned from
the sql transaction:
Eriends>ithBeer<B!runFuer0(sGl, function(records) {
for (var i=4% i9records.le"gth% i..# {
&
})%
4 - 2#
2013 Intel Corporation.
Workin wit! Data
<K1 .nside the for;loop, append dynamically generated list items to the
Listie!1 8our code should appear as follo!s:
Eriends>ithBeer<B!runFuer0(sGl, function(records) {
for (var i=D% i/records!length% i++) {
var item = records3i5%
list.appe"d(
(eer!emplate.format(
item.id,
item.cou"try,
item."ame,
item.thecou"t
#
#%
}
})%
<L1 .mmediately after the for;loop, refresh the list1
list.listvie$(1refresh1#%
<M1 &a#e the file and test the app in the emulator1 8ou should see the full
list of beers appear on the Eeers tab1
En$ o& 'al(through 6
4 - 2$
2013 Intel Corporation.
Fast Track to Intel XDK New
-%porting Data $ro% the *ontacts .ist
.ntel 4'F 5e! supports Apache *ordo#a, !hich acts as a bridge that
enables you to use /a#ascript to access nati#e de#ice resources1 One of
those resources is the de#ice)s contacts list1
&ince contact information is generally considered to be pri#ate and
personal, your app)s pri#acy policy should discuss ho! your app uses this
data and !hether it !ill be shared !ith other parties1 8ou should also
strongly consider pro#iding a just;in;time notice prior to your app
accessing or using contact data 2if the de#ice operating system doesn)t do
so already31
"he *ordo#a A9. enables you to both read and !rite to the de#ice)s
*ontacts list1
Aull documentation on this A9. is at the follo!ing U(L:
http:NNcordo#a1apache1orgNdocsNenNG1M1=Ncordo#aRcontactsRcontacts1md1htm
lS*ontacts
.oa,ing the *or,ova .ibrar3
8ou)ll need to load the *ordo#a ja#ascript library, cordo#a1js, in order to
access *ordo#a)s *ontacts List A9.1
"he cordo#a1js file is dynamically injected into the root of your application
during the EU.L' process1 All you need to do is add the follo!ing element
to the top of your inde,1html file)s 6head7 section:
9script type=1text'javascript1 src=1cordova.js1;9'script;
+an,ling Ti%e0-ntensive !s3nchronos Operations
(etrie#ing contacts can be a time;intensi#e operation, depending on the
speed of the de#ice and the number of contacts that the user has stored1
-hen dealing !ith asynchronous operations, it is often useful to pro#ide
the user !ith feedback that they should !ait for a function to complete
before proceeding1 /query)s Loader !idget !orks !ell in these scenarios1
.nstantiate the loader using the follo!ing synta,:
$.mo(ile.loadi"g( 'sho$', {
text: 12lease Hait1,
textMisi(le: true,
theme: 1a1,
texto"ly: false,
html: 11
&#%
Use the follo!ing synta, to hide the loader:
$.mo(ile.loadi"g( 1hide1 #%
4 - 2%
2013 Intel Corporation.
Workin wit! Data
Retrieving *ontact Recor,s
*ontacts1find23 queries the de#ice contacts database asynchronously and
returns an array of *ontact objects !hich are passed to a callback function1
"he basic synta, is:
"avigator.co"tacts.fi"d(
co"tactSields, ''array of field "ames to search (reRuired#
co"tact*uccess, '' success call(ac0 fu"ctio" (reRuired#
co"tactrror, '' failure call(ac0 fu"ctio" (optio"al#
search,ptio"s '' ,ptio"s to filter co"tacts (optio"al#
#%
5ote the follo!ing:
Only the fields specified in the contactAields parameter !ill be
returned as properties of the *ontact objects that are passed to the
contact&uccess callback function1
A contactAields #alue of TOUOV !ill return all contact fields1
A @ero;length contactAields parameter is in#alid and !ill result in a
*ontact+rror1.5AL.'RA(?UM+5"R+((O(1
"he follo!ing e,ample returns contacts named D&te#eC:
var optio"s = "e$ Oo"tactSi"d,ptio"s(#%
optio"s.filter=1*teve1%
var fields = 31display-ame1, 1"ame15%
"avigator.co"tacts.fi"d(
fields,
fu"ctio"(co"tacts# {
alert(co"tacts.le"gth . 1 records fou"d=1#%
for (var i=4% i9co"tacts.le"gth% i..# {
alert(1Gisplay -ame = 1 . co"tacts3i5.display-ame#%
&
&,
fu"ctio"(err# {
alert(1>mport Sailed1#%
&,
optio"s
#%
4 - 2&
2013 Intel Corporation.
Fast Track to Intel XDK New
Working with *ontact Data
8ou can read the follo!ing fields for each contact record:
Fiel$ 1escription
id
&tring1 A globally unique identifier
displa0*a"e
&tring1 "he name of the *ontact, suitable for display
to end;users
na"e
Object An object containing all components of a
persons name1
nicna"e
&tring1 A casual name to address the contact1
addresses
Array1 All of the contact)s addresses1
phone*u"$ers
Array1 *ontact)s phone numbers
e"ails
Array1 All of the contact)s email addresses
i"s
Array1 All of the contact)s instant messaging addresses
organizations
Array1 All of the contact)s organi@ations
$irthda0
'ate1 "he contact)s birthday1
note
&tring1 ?eneral remarks about the contact1
photos
Array1 "he contact)s photos1
categories
Array1 All of the contact)s user;defined categories1
urls
Array1 An array of !eb url)s associated !ith the
contact1
8ou !ould use the follo!ing synta, to output a contact)s display name to
an alert bo,:
o"*uccess: fu"ctio"(co"tacts# {
for (var i=4% i9co"tacts.le"gth% i..# {
$i"do$.alert(co"tacts3i5.display-ame#%
&
&
4 - 30
2013 Intel Corporation.
Workin wit! Data
)arsing the *ontact (a%e
"he *ontact 5ame is a ja#ascript object containing the follo!ing
properties:
Fiel$ 1escription
for"atted
&tring1 "he complete name of the contact1
fa"il0*a"e
&tring1 "he contact)s family name1
given*a"e
&tring1 "he contact)s gi#en name1
"iddle*a"e
&tring1 "he contact)s middle name1
honorificPrefix
&tring1 "he contact)s prefi, 2Mr1 N 'r1 N Mrs1 N etc3
honorific(uffix
&tring1 "he contact)s suffi,, e1g1 +sq, ''&, M'
"o output a contact)s first name follo!ed by their last name, you !ould use
the follo!ing synta,:
o"*uccess: fu"ctio"(co"tacts# {
for (var i=4% i9co"tacts.le"gth% i..# {
$i"do$.alert(
''.co"cat(
co"tacts3i5."ame.give"-ame,
' ',
co"tacts3i5."ame.family-ame
#
#
&
&
4 - 31
2013 Intel Corporation.
Fast Track to Intel XDK New
)arsing the *ontact8s !,,resses
+ach *ontactAddress object has the follo!ing properties:
Property 1escription
pref
Eoolean1 "rue if the contact)s preferred address1
t0pe
&tring1 .ndicates type of address, e1g1 )home)
for"atted
&tring1 "he full address, formatted for display1
street;ddress
&tring1 "he full street address1
localit0
&tring1 "he city or locality1
region
&tring1 "he state or region1
postalHode
&tring "he @ip code or postal code1
countr0
&tring1 "he country name1
"o determine the preferred address, you)ll need to loop through the
contact)s addresses array as illustrated by the follo!ing snippet:
o"*uccess: fu"ctio"(co"tacts# {
for (var i=4% i9co"tacts.le"gth% i..# {
var address = 11%
for (var j=4% j9co"tacts3i5.addresses.le"gth% j..# {
if (co"tacts3i5.addresses3j5.pref# {
address = co"tacts3i5.addresses3j5%
(rea0%
&
&
alert(address.formatted#%
&
&
4 - 32
2013 Intel Corporation.
Workin wit! Data
)arsing the *ontact8s E%ail !,,resses an, )hone (%bers
+mail addresses and phone numbers are stored in a *ontactAield objects
!hich contains the follo!ing properties:
Property 1escription
type &tring1 "he type of field, e1g1 )home),)!ork),)mobile)
#alue &tring1 "he email address or phone number
pref Eoolean1 .f true, represents the preferred #alue1
"he follo!ing e,ample illustrates ho! to retrie#e the preferred phone
number:
o"*uccess: fu"ctio"(co"tacts# {
for (var i=4% i9co"tacts.le"gth% i..# {
var pho"e = 11%
for (var j=4% j9co"tacts3i5.pho"e-um(ers.le"gth% j..# {
if (co"tacts3i5.pho"e-um(ers3j5.pref# {
pho"e = co"tacts3i5.pho"e-um(ers3j5.value%
(rea0%
&
&
alert(pho"e#%
&
&
4 - 33
2013 Intel Corporation.
Fast Track to Intel XDK New
Testing *ontact 4eatres
Accessing the *ontact)s list is a de#ice;specific feature1 8ou !ill not be
able to access this functionality through either the emulator or .ntel App
9re#ie!1 8ou can only test your code by creating a nati#e build1
Also, note that in the 'etails configuration tab of the Euild panel, you)ll
need to turn on the option labeled D"his App Accesses the User)s *ontactsC
as illustrated in Aigure <=1
4 - 34
2013 Intel Corporation.
Figure 1@: *nclu$ing the Contacts li5rary in your nati,e 5uil$.
Workin wit! Data
Walkthrogh 404: .oa,ing *ontacts
.n this !alkthrough, you !ill add a button to the DAriendsC screen that
enables a user to import their de#ice)s contacts into the Ariends !ith Eeer
app1
Access de#ice contacts
"ransfer contact data into a -eb&QL table
Use the !einre debugger to #erify your !ork
'teps
Open the )roject
<1 Open .ntel 4'F 5e!
G1 *lick on the !ord PROJECTS in the top;left corner of the ?U.1
H1 *lick the Open a Proect button1
I1 &elect the follo!ing file:
/ft6ntel@d*e#/#al/#alABA/#alABA!xd
!,, the -%port 9tton
%1 Open Contacts.ht!l in 'esign ie!
J1 Arom the *ontrols 7 Aorm palette, drag a "utton !idget and drop it on
the left edge of the Frien$s header1
K1 *onfigure the follo!ing "utton properties:
Label: .mport
.con: ui;icon;user
.con 9osition: icon only
id: btn.mport*ontacts
.oa, the *or,ova !)-
L1 Open in$e?.ht!l in *ode ie!
M1 -here indicated by the comment, insert a AscriptB tag to load the file
cordo#a1js
Review the *ontacts Object
<=1 -here indicated by the comment, re#ie! the *ontacts object and its
method)s associated comments1
4 - 3"
2013 Intel Corporation.
Fast Track to Intel XDK New
<<1 .nside the *ontacts init23 method, define an e#ent listener for the tap
e#ent on the 5tn*!portContacts button1
init: function() {
$(1I(t">mportOo"tacts1#.(i"d(1tap1, fu"ctio"(e# {
&
}
<G1 .nside the tap e#ent handler, insert an i&%else block that determines
!hether the na,igator.contacts object e,ists1
.f na#igator1contacts does not e,ist, display an alert23 message that
informs the user that the feature is not a#ailable1
init: function() {
this!initialized = true%
&("I$tn6"portHontacts")!$ind("tap", function(e) {
if ("avigator.co"tacts# {
& else {
alert(1Su"ctio" "ot availa(le1#%
&
}
}
<H1 .nside the if;block, insert a !indo!1prompt23 that asks the user for the
name of the contact that they !ant to import1 .f the user enters a
response, pass it along to the import*ontacts method of the *ontacts
object1
init: function() {
this!initialized = true%
&("I$tn6"portHontacts")!$ind("tap", function(e) {
if (navigator!contacts) {
var frie"d-ame = $i"do$.prompt(
1"ter your frie"d's "ame1,
11
#%
if (frie"d-ame == "ull# {
Oo"tacts.importOo"tacts(frie"d-ame#%
&
} else {
alert("Eunction not availa$le")%
}
}
}
<I1 &a#e the file and test in the +mulator1 8ou should see a DAunction not
a#ailableC message !hen attempting to import contacts from the
emulator1
4 - 3#
2013 Intel Corporation.
Workin wit! Data
'earch $or *ontacts
<%1 (eturn to 'e#elop mode1
<J1 .nside the i!portContacts function, display a D9lease -aitC message
to the user1
$.mo(ile.loadi"g( 'sho$', {
text: 12lease Hait1,
textMisi(le: true,
theme: 1a1,
texto"ly: false,
html: 11
&#%
<K1 After the code that you inserted in the prior step, define a local #ariable
named options that is a ne! *ontactAindOptions object1
var optio"s = "e$ Oo"tactSi"d,ptio"s(#%
<L1 &et the &ilter property of the options object to the #alue of the
argument that !as passed into the function1
optio"s.filter=frie"d-ame%
<M1 &et the !ultiple property of the options object to retrie#e multiple
contact records1
optio"s.multiple = true%
G=1 'efine a local #ariable named fields that contains an array of strings
for the contact information that you need to retrie#e 2name, address,
phone, email3:
var fields = 3
1display-ame1,
1"ame1,
1addresses1,
1pho"e-um(ers1,
1emails1
5%
G<1 .n#oke the na#igator1contacts1find23 method as illustrated belo!:
"avigator.co"tacts.fi"d(fields,
this.o">mport,
this.o">mportrror,
optio"s#%
De$ine the *ontact8s 'earch 'ccess +an,ler
GG1 .nside the on*!port method, hide the D9lease -aitC message1
$.mo(ile.loadi"g( 1hide1 #%
GH1 After the code that you inserted in the prior step, define the follo!ing
local #ariables:
address B null
phone B null
email B null
count B =
friend B null
4 - 3$
2013 Intel Corporation.
Fast Track to Intel XDK New
GI1 After the code that you inserted in the prior step, insert a for;loop to
iterate through the contacts data returned to the function1
for (var i=4% i9co"tacts.le"gth% i..# {
&
G%1 .nside the for;loop, insert an if23 block that checks if the contact)s gi#en
name is not undefined1
if (co"tacts3i5."ame.give"-ame == u"defi"ed# {
&
GJ1 .nside the for;loop, increment the count #ariable by <1
if (contacts7i:!na"e!given*a"e J= undefined) {
cou"t..%
}
Retrieve the *ontact8s (a%e
GK1 After the code that you inserted from the prior step, set the #ariable
&rien$ equal to an array containing t!o objects !ith t!o properties P
na!e and ,alue1
.n the first object, the name should be equal to Dfirst5ameC and the
#alue property should equal the contact)s gi#en name1
.n the second object, the name should be equal to Dlast5ameC and
the #alue property should equal the contact)s family name1
for (var i=D% i/contacts!length% i++) {
if (contacts7i:!na"e!given*a"e J= undefined) {
count++%
var frie"d = 3
{
"ame: 1first-ame1,
value: co"tacts3i5."ame.give"-ame
&,
{
"ame: 1last-ame1,
value: co"tacts3i5."ame.family-ame
&
5%
}
}
*aptre the )ri%ar3 *ontact !,,ress
GL1 After the code that you inserted in the prior step, insert a conditional
that checks for the e,istence of a contact)s address1
if (co"tacts3i5.addresses# {
&
4 - 3%
2013 Intel Corporation.
Workin wit! Data
GM1 .nside the if23 block, set the address #ariable equal to the result from
calling the *ontacts1get9referred23 method, passing in the contact)s
addresses1
if (contacts7i:!addresses) {
address = Oo"tacts.get2referred(co"tacts3i5.addresses#%
}
H=1 .mmediately after the code that you inserted in the prior step, add the
resulting street address and @ipcode to the friends array as indicated
belo!:
if (contacts7i:!addresses) {
address = Oo"tacts.get2referred(co"tacts3i5.addresses#%
frie"d.push(
{ "ame: 1address1, value: address.street)ddress&
#%
frie"d.push(
{ "ame: 17ipcode1, value: address.postalOode&
#%
}
2et the *ontact8s )ri%ar3 )hone (%ber
H<1 After the contact)s .A block, insert another conditional that e#aluates
!hether or not any phone numbers e,ist for the contact1
if (co"tacts3i5.pho"e-um(ers# {
&
HG1 .nside the if23 block, push another object onto the friend array that
contains the contact)s preferred phone number1
if (co"tacts3i5.pho"e-um(ers# {
frie"d.push(
{
"ame: 1pho"e1,
value:
Oo"tacts.get2referred(co"tacts3i5.pho"e-um(ers#.value&#%
&
#
&
2et the *ontact8s )re$erre, E%ail !,,ress
HH1 After the if23 block that you inserted from the prior steps, insert another
conditional that e#aluates !hether the contact object has an emails
property1
if (co"tacts3i5.emails# {
&
4 - 3&
2013 Intel Corporation.
Fast Track to Intel XDK New
HI1 .nside the if23 block, push another object containing user)s preferred
email address onto the &rien$ array1
if (co"tacts3i5.emails# {
frie"d.push(
{
"ame: 1email1,
value: Oo"tacts.get2referred(co"tacts3i5.emails#.value&#%
&
#
&
'ave the 4rien, Object to the Database
H%1 .mmediately after the last if23 block, !rite the data from the friend
object to your -eb&QL database1
Srie"dsHith<eerG<.$riteDecord('frie"d',"ull, frie"d#%
HJ1 .mmediately outside the for;loop in the on.mport23 method, output the
#alue from the count #ariable to the user in an alert bo,1
alert(cou"t . 1 Oo"tacts >mported1#%
Test 3or Work on :or Device
HK1 &a#e the file1
HL1 *lick on the Test tab1
HM1 *lick the Push Files button1
I=1 Open *ntel App Pre,ie- on your phone1
I<1 *lick the Ca!era icon and focus the camera on the Q( code1
IG1 *lick OC1
IH1 *lick the Frien$s button1
II1 *lick the *!port Contacts button1
I%1 +nter the first or last name of one of your friends !ho are in your
de#ice)s *ontacts list1
IJ1 "ap OC1
IK1 (eturn to .ntel 4'F 5e!
IL1 *lick "egin 1e5ugging on 1e,ice1
IM1 *lick on the "arget hyperlink
%=1 *lick on the (esources tab1
%<1 Open the Ariends-ithEeer database and confirm that data is present in
the Ariend table1
6 En$ o& 'al(through %%
4 - 40
2013 Intel Corporation.
Workin wit! Data
Unit '%%ar3
jQuery Mobile enables you to make e,ternal data requests to remote
ser#ices using either A/A4 or /&O5;9 protocols1
All data requests are handled asynchronously1
erify that data !as retrie#ed correctly by outputting the ser#er
response to the debugger using console1log23
-eb apps !ill not be able to make cross;domain requests unless the
remote host supports cross;origin resource sharing 2*O(&3
Most data requests should be deferred until they are specifically
requested by the user1
*ompartmentali@e your code by attaching properties and methods to
/a#ascript objects1
(emote data can be cached in bro!ser memory or persisted in html%
local&torage or -eb&QL databases1
Use the Listie! !idget to output lists of data1
8ou can listen for tap e#ents on list items and then programmatically
retrie#e properties associated !ith the item that !as tapped1
"he *ordo#a A9. gi#es you access to hard!are resources, including
the *ontacts list1
Most *ordo#a A9. functionality must be tested on physical de#ices
and may not function properly in the emulator1
4 - 41
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Review
<1 A/A4 requests can only be made to the same domain that a !eb app is
hosted on 2trueNfalse31
G1 /&O5;9 requests cannot read 4ML data 2trueNfalse3
H1 8ou can 9O&" data #ia /&O5;9 2trueNfalse31
I1 "he Listie! search filter can only search for data that)s #isible to the
user1
%1 &tring1format23 is a nati#e /a#ascript method 2trueNfalse3>
J1 -hy do data requests typically require that you supply a callback
function>
K1 -hich hard!are resources can only be accessed #ia the *ordo#a A9.>
4 - 42
2013 Intel Corporation.
Workin wit! Data
.ab 4: Working with .ists an, Web'&.
'uring this lab you !ill read data from your -eb&QL database and display
it in a dynamically populated list #ie!1
Objectives
After completing this lab, you should be able to:
(ead data from a -eb&QL database
'ynamically construct a list #ie!
'teps
<1 Open ;la5;la5.;la5..?$(
G1 Open contacts1html
H1 'rag a L.&".+- !idget onto the design can#as and configure its
properties1
I1 (eturn to inde,1html
%1 Modify the *ontact)s displayList23 method to output data from the
-eb&QL table into the L.&".+- that you defined from step H1
J1 Modify the on.mport23 method to refresh the L.&".+- after your
contacts ha#e been imported1
P +nd of Lab ;;
4 - 43
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 5:
Creating Input Forms
Unit Objectives
After completing this unit, you should be able to:
Create a data entry form
Pre-fill form fields with data
Populate a <select> control with data from a webservice
Validate data input
ransmit form data to an application server
!ave form data to a "eb!#$ database%
Unit Topics
Creating &orms
Validating &orm 'nput
Persisting &orm (ata
5 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Creating Forms
'ntel )(* +ew supports the following types of form fields:
Chec,bo-
Chec,bo- .roup
&lip !witch
e-t
/idden
!lider
(ate
0mail Address
elephone +umber
Password
!earch
!elect
e-t Area
+umber
(atetime
1onth
23$
3adio
3adio .roup
Working with Text Fiels
/1$4 e-tends the standard te-tfield from /1$ 5%67 by adding the
following easily deployed features:
Automatically set focus
!pecify placeholder te-t
Validate that data was input in a specific format
!ome of these capabilities are directly supported by the 'ntel )(* +ew
.2' as depicted in &igure 7% 8thers you will need to add using code view%
5 - 2
2013 Intel Corporation.
Figure 1: Configuring Text Fields with Intel XDK New
Creating Inpt For!s
!utomaticall" #etting Focus
he /1$ 4 autofocus attribute enables you to set focus to a specific form
field as soon as the form is rendered in your browser% 'n /1$ 5 this
could only be accomplished by using 9ava!cript:s focus;< method%
he following e-ample sets focus to a te-t field:
<form>
<label for="myfield">
This field will automatically have cursor focus:
</label>
<input type="text" name="myfield" autofocus />
</form>
#peci$"ing %laceholer Text
Placeholder te-t helps you ma,e your forms more intuitive and usable by
allowing for descriptive te-t to be placed inside of a te-t field via the
placeholder attribute% 8nce the field has focus or has a value, the
placeholder te-t is removed%
<form>
<label for="lastname">Enter your last name:</label>
<input type="text"
name="lastname"
placeholder="Last Name" />
</form>
As depicted in &igure =, the placeholder is fre>uently used in lieu of a label
in order to conserve space% ?ou can >uic,ly implement this feature by
turning on the placeholder chec,bo- in the )(* New interface%
5 - 3
2013 Intel Corporation.
Figure 2: Placeholders help ou conser!e space"
Fast Track to Intel XDK New
Capturing &mail !resses
2sing <input type=email> automatically ad@ust the user:s on-screen
,eyboard to facilitate data entry%
<form>
<label for="myemail">Enter your e-mail address:</label>
<input type="email" name="myemail"
placeholder="me@mycompany.com" />
<input type="submit">
</form>
As depicted in &igure =, you can define an email field by dragging an input
widget onto the design canvas and then specifying email as its type%
Inputting %hone 'umbers
2se <input type=tel> to enable a user to
easily enter a telephone number% 1obile browsers
automatically present the user with a phone ,eypad
to facilitate input into this field type%
<form>
<input
type="tel"
name="phone"
placeholder="el" />
<input type="submit">
</form>
5 - "
2013 Intel Corporation.
Figure #: Defining an e$ail input field"
Figure %: The tel field
in i&'
Creating Inpt For!s
Using #elect (enus
he select menu hides the default html
<select> control and replaces it with a
custom-styled select button that matches
the loo, and feel of the @#uery 1obile
framewor,% he select menu is fully
accessible to people with disabilities%
"hen pressed, select menu options will
render using the native format of the
device% "hen a value is selected and the
menu closes, the custom button:s te-t is
updated to match the selected value%
he synta- generating a @#uery !elect
1enu is the same as generating a standard
/1$ <select> control:
<select name="beerid"
id="beerid">
<option !alue=""">#mstel</option>
<option !alue="$">%ud&eiser</option>
<option !alue="'">(himay )ou*e</option>
<option !alue="+">(orona E,tra</option>
</select>
!ing a %laceholer Option
?ou:ll typically want to include a AnullA option in your select element to
force a user to choose an option% Placeholder options are automatically
hidden by @#1 in the overlay menu, thereby ensuring that only valid
choices are presented to the user% Placeholders are recogniBed as:
An option with no value attribute or an empty value attribute
An option with no te-t node
An option with a dataplaceholder="true" attribute%
he following e-ample illustrates using a placeholder:
<select name="beerid" id="beerid">
<option>-elect a %eer</option>
<option !alue=""">#mstel</option>
<option !alue="$">%ud&eiser</option>
<option !alue="'">(himay )ou*e</option>
<option !alue="+">(orona E,tra</option>
</select>
5 - 5
2013 Intel Corporation.
Figure (: ) *+, 'elect ,enu"
Fast Track to Intel XDK New
)"namicall" !ing Options to a #elect (enu
Adding dynamic options to a !elect menu is >uite similar to adding
dynamic rows to a $istView widget% As illustrated by the following code
snippet, use @#uery:s append;< method to attach dynamically created
<option> elements to a <select> control and then invo,e the widget:s
refresh;< method to have those changes appear on-screen%
!ar beers = .
/
label: "#mstel Li*ht"0
!alue: "
10
/
label: "(orona E,tra"0
!alue: $
1
23
!ar 4y-elect = 56"select7beerid"83
!ar tpl = 9<option !alue="/:1">/"1</option>93
// remo!e all items
4y-elect.empty683
// add placeholder
4y-elect.append6tpl.format69909;lease -elect9883
// add data items
for 6!ar i=:3 i<beers.len*th3 i<<8 /
4y-elect.append6tpl.format6
ships.i2.!alue0
ships.i2.label
883
1
// important: refresh the list===
4y-elect.selectmenu6"refresh"0 true83
5 - #
2013 Intel Corporation.
Creating Inpt For!s
Walkthrough 5*+: )esigning a Form
'n this wal,through, you will start developing a
data input form to enable the user to edit their
contacts and lin, their contacts to a specific
brand of beer%
(esign a form
(ynamically populate a <select> list
'mplement a CDac,E button
3espond to button taps
#teps
Open the %roject
7% 8pen 'ntel )(* +ew
=% Clic, on the word P-&./CT' in the top-
left corner of the .2'%
F% Clic, the &pen a Pro*ect button%
5% !elect the following file:
/ft>ntel?d@Ne&/&al@/&al@AB"/&al@AB".,d@
)e$ine the ,eaer -uttons
4% 8pen the contactform%html file in (esign mode%
G% &rom the Controls > &orm palette, drag a button widget and drop it on
the left edge of the page header%
H% Configure the following properties:
'con: ui-icon-bac,
'con position: icon only
id: btnDac,
I% .o to Code mode%
J% $ocate the anchor tag that was generated for the bac, button and add
the following attribute:
data-rel="bac@"
76% 3eturn to (esign mode%
77% &rom the Controls > &orm palette, drag a button widget and drop it on
the right edge of the page header%
5 - $
2013 Intel Corporation.
Figure 0: The data entr
for$ that ou will create
during this exercise
Fast Track to Intel XDK New
7=% Configure the following properties:
'con: ui-icon-chec,
'con Position: 'con only
id: btn!ave
)e$ine the Form
7F% &rom the Controls > 1aout panel, drag a -ow widget and drop it
onto the center of the design canvas%
75% Configure the following property:
is For$: chec,ed
)e$ine the Contact Fiels
74% &rom the Controls > For$ palette, drag an Input widget and drop it
onto the 3ow widget in the (esign Canvas%
7G% Configure the following properties:
$abel: ;unchec,ed<
ype: te-t
Placeholder: &irst +ame
+ame: first+ame
id: first+ame
7H% &rom the Controls > &orm palette, drag an 'nput widget and drop it
directly underneath the &irst +ame field on the (esign Canvas%
7I% Configure the following properties:
$abel: ;unchec,ed<
ype: te-t
Placeholder: $ast +ame
+ame: last+ame
id: last+ame
7J% &rom the Controls > &orm palette, drag an 'nput widget and drop it
directly underneath the $ast +ame field on the (esign Canvas%
=6% Configure the following properties:
$abel: ;unchec,ed<
ype: te-t
Placeholder: !treet Address
+ame: address
id: address
=7% &rom the Controls > &orm palette, drag an 'nput widget and drop it
directly underneath the Address field on the (esign Canvas%
==% Configure the following properties:
$abel: ;unchec,ed<
5 - %
2013 Intel Corporation.
Creating Inpt For!s
ype: number
Placeholder: Kip Code
+ame: Bipcode
id: Bipcode
=F% &rom the Controls > &orm palette, drag an 'nput widget and drop it
directly underneath the Kip Code field on the (esign Canvas%
=5% Configure the following properties:
$abel: ;unchec,ed<
ype: email
Placeholder: youLyou%com
+ame: email
id: email
=4% &rom the Controls > &orm palette, drag an 'nput widget and drop it
directly underneath the email field on the (esign Canvas%
=G% Configure the following properties:
$abel: ;unchec,ed<
ype: telephone
Placeholder: el
+ame: phone
id: phone
Create a )"namicall" %opulate #elect .ist
=H% &rom the Controls > For$ palette, drag a 'elect widget and drop it
directly underneath the telephone field on the (esign Canvas%
=I% Configure the following properties:
$abel: ;unchec,ed<
8ptions: !elect a Deer
+ame: beer'd
id: beer'd
=J% !ave the file
F6% 8pen index"ht$l in Code mode%
F7% "here indicated by the comment, define a 9ava!cript ob@ect named
Contact&orm%
!ar (ontactCorm = / 13
F=% (efine the following property on the Contact&orm ob@ect:
friend>d: null3
FF% Add the following methods to the Contact&orm ob@ect:
init
populateDeer&ield
F5% 3eview your code to ensure that it appears similar to the following:
5 - &
2013 Intel Corporation.
Fast Track to Intel XDK New
!ar (ontactCorm = /
friend>d: null0
init: function68 /
10
populate%eerCield : function68 /
1
13
F4% 'nside the initialiBe;< method, call the populateDeer&ield method%
var !ontact"orm = #
init: function$% #
this.populate%eerCield683
&'
populate(eer"ield : function$% #
&
&)
FG% 'nside the populateDeer&ield;< method, define a local variable named
beer&ield that points to the beerid select widget in the form% ?our code
should appear similar to the following:
!ar beerCield = 56"select7beer>d"83
FH% After the code that you inserted from the prior step, insert a for-loop
that loops through the beer data that:s cached in the variable App%beers%
populate(eer"ield : function$% #
var beer"ield = *$"select+beer,d"%)
for 6!ar i=:3 i< #pp.beers.len*th3 i<<8 /
1
&
FI% 'nside the for-loop, insert code that dynamically outputs the data from
App%beers as <option> elements inside of the select widget%
populate(eer"ield : function$% #
var beer"ield = *$"select+beer,d"%)
for $var i=-) i< .pp/beers/len0th) i11% #
beerCield.append6
9<option !alue="/:1">/"1</option>9.format6
#pp.beers.i2.id0
#pp.beers.i2.name
8
83
&
&
FJ% After the for-loop, insert a statement to refresh the display of the select
widget%
beerCield.selectmenu6"refresh"0 true83
56% !ave the file%
! a /! Contact0 button to the Contacts .ist
57% 8pen the contacts%html page in (esign mode%
5 - 10
2013 Intel Corporation.
Creating Inpt For!s
5=% &rom the Controls > &orm palette, drag a button widget and drop it on
the right edge of the page header%
5F% Configure the following properties:
'con: ui-icon-plus
'con Position: 'con only
id: btnAdd
55% .o to Code mode and locate the generated mar,up for the button%
54% Add the following attributes to the anchor tag that wraps the add
button:
hrefMEcontactform%htmlE
data-transitionMEflipE
5G% !ave the file%
5H% 3eturn to inde-%html in Code mode%
5I% 'n the Contacts ob@ect, at the end of the init;< method, bind a tap event
handler to the CAdd ContactE button%
56"7btn#dd"8.bind6"tap"0 function6e8 /
183
5J% 'nside the button tap callbac, function, set the friend'd property in the
Contact&orm ob@ect to null%
*$"+btn.dd"%/bind$"tap"' function$e% #
(ontactCorm.friend>d = null3
&%)
46% !ave the file and test in the emulator%
N 0nd of "al,through --
5 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
1aliating Form Input
2nfortunately, mobile browsers do not support the native form field
validation properties that are stipulated as part of the /1$4 specification%
?ou can adapt the @#uery Validation Plugin, however, to easily ensure that
users are entering data in the format that you intended%
he @#uery Validation Plugin is maintained by 9Orn Kaefferer, a member
of the@#uery team, lead developer on the @#uery 2' team and maintainer of
#2nit% 't was started bac, in the early days of @#uery in =66G, and updated
and improved since then%
he plugin comes bundled with a useful set of validation methods,
including 23$ and email validation, while providing an AP' to write your
own methods% All bundled methods come with default error messages in
english and translations into FH other languages%
't:s free to use under an 1' license and hosted at
http:PP@>ueryvalidation%orgP
he plugin validates the following patterns for correctness:
Tpe Description
re2uired
1a,es data input re>uired%
remote
3e>uests a resource chec, the element for validity%
minlen0th
3e>uires strings to be a specified minimum length
ran0elen0th
3e>uires strings to be within a specified siBe range%
email
3e>uires the string to be a properly formatted email
address%
url
3e>uires the input string to be a properly formatted url%
date
3e>uires the input string to be a valid date%
date,34
3e>uires the input to be a properly formatted '!8 date
number
3e>uires the input to be a decimal number
di0its
1a,es the element re>uire numeric values only%
creditcard
Validates that the creditcard number has been properly
formatted%
e2ualTo
3e>uires the input data in one field be identical to the
input data in another field%
't also comes with e-tensions to validate other data types as well, including
2! phone numbers%
5 - 12
2013 Intel Corporation.
Creating Inpt For!s
.oaing the .ibrar"
?ou can load the @#uery Validation $ibrary ;@>uery%validate%@s< by simply
inserting a <script> tag into your document:s <head> section:
<head>
///
<script type="text/5avascript"
src="5s/52uery/min/5s"></script>
<script type="text/5avascript"
src="52m/52uery/mobilemin/5s"></script>
<script type="te,t/Da!ascript"
src="Ds/DEuery.!alidate.Ds"></script>
</head>
!ing 1aliation 2ules to Form Fiels
?ou can add validation rules to fields by invo,ing the form%validate;<
method which re>uires a @avascript ob@ect that defines rules, behaviors, and
other options%
ypical validate;< invocations appear as follows:
56 "7myform" 8.!alidate6/
submitFandler: function6form8 /
56form8.aDa,-ubmit683
10
in!alidFandler: function6e!ent0!alidator8 /
!ar errors = !alidator.numberGf>n!alids683
alert6">n!alid data in " < errors < " fields"83
10
rules: /
lastName: /
reEuired: true
1
10
messa*es: /
lastName: ";lease enter you family name"
1
183
'n the preceding snippet, note the following:
he su2$it3andler is invo,ed when the the user presses the form:s
submit button and all form fields pass validation%
he in!alid3andler is called when the form is submitted when the
user presses the form:s submit button but not all fields have passed
validation%
he rules ob@ect defines data validation rules on form fields% 'n this
case, Clast+ameE is the id of a te-t field%
he $essages ob@ect enables you to define custom validation error
messages%
5 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
2e3uiring )ata Input
?ou can re>uire data input on a field by adding the re>uired attribute to any
<input> field as illustrated below:
<label class="narrowcontrol" for="last6ame"></label>
<input class="widecontrol"
placeholder="7ast 6ame"
type="text"
name="last6ame"
id="last6ame"
reEuired >
?ou can also attach the re>uired validation rule to a field by invo,ing a
form:s validate;< method ;in@ected by the plugin<:
56 "7myform" 8.!alidate6/
rules: /
lastName: /
reEuired: true
1
1
183
1aliating &mail !resses
3e>uire that a properly formatted email address be entered into a form field
by applying the following validation rules:
<label class="narrowcontrol" for="email"></label>
<input class="widecontrol"
placeholder="me8myemailaddress/com"
type="text"
name="useremail"
id="userEmail">
56 "7myform" 8.!alidate6/
rules: /
userEmail: /
reEuired: true0
email: true
1
1
183
5 - 1"
2013 Intel Corporation.
Creating Inpt For!s
1aliating #tring .ength
?ou can set validation on string field length by using the rangelength
validator as illustrated below:
<label class="narrowcontrol" for="last6ame"></label>
<input class="widecontrol"
placeholder="7ast 6ame"
type="text"
name="last6ame"
id="last6ame">
*$ "+myform" %/validate$#
rules: #
last6ame: #
re2uired: true'
ran*elen*th: .$0$:2
&
&
&%)
1aliating 'umeric Input
3e>uire that input data may only contain characters in the range of 6-J by
applying the digits rule as noted below:
<label class="narrowcontrol" for="9ip"></label>
<input class="widecontrol"
placeholder="9ip code"
type="text"
name="9ipcode"
id="9ipcode">
56 "7myform" 8.!alidate6/
rules: /
Hipcode: /
reEuired: true0
di*its: true
1
1
183
%rogrammaticall" &xecute 1aliation 2ules
?ou can invo,e form field validating programmatically by invo,ing the
validator%form;< method as illustrated below%
!ar !alidator = 56"form7contactform"8.!alidate683
!alidator.form683
5 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
Con$iguring 1aliation (essage %lacement an Theming
Dy default, error validation messages are in@ected into the form field:s
<label> element% ?ou can modify this behavior on a field-level basis by
specifying an errorPlacement method% he following e-ample moves the
validation method into a parent <div> for a <select> element with an id of
CbeeridE:
!ar form = 56"form7contactform"83
form.!alidate6/
error;lacement: function6error0 element8 /
if 6element.attr6"name"8 === "beerid"8 /
error.insert#fter656element8.parent6883
1 else /
error.insert#fter6element83
1
1
183
As illustrated in the following snippet, you can style the error message by
defining a css class on the label%error selector%
label.error /
float: left3
color: red3
paddin*-top: .Aem3
!ertical-ali*n: top3
font-&ei*ht:bold
1
5 - 1#
2013 Intel Corporation.
Creating Inpt For!s
Walkthrough 5*4: Implementing Form 1aliation
'n this wal,through you will add data input
validation rules to the contact form%
$oad the @#uery Validation plugin%
(efine validation rules for form fields
CustomiBe the display of error messages
Programmatically trigger form validation
#teps
Open the %roject
7% 8pen 'ntel )(* +ew
=% Clic, on the word P-&./CT' in the top-left corner of the .2'%
F% Clic, the &pen a Pro*ect button%
5% !elect the following file:
/ft>ntel?d@Ne&/&al@/&al@AB$/&al@AB$.,d@
! an I) %ropert" to 5our Form
4% 8pen the contactform%html file in Code view%
G% Add the following attribute to the 4for$5 element:
id="contactform"
)e$ine the 1aliation 2ules
H% 8pen the inde-%html file in Code mode%
I% 8n line F5, insert a <script> tag to load the @#uery Validation library%
<script type="te,t/Da!ascript"
src="Ds/DEuery.!alidate.Ds"></script>
J% 'nside the ContactFor$ ob@ect, underneath the populate6eerField
method, define a function named init7alidation%
76% 'nside the init7alidation method, define a local variable named for$
that points to the form that you defined in the prior wal,through%
!ar form = 56"form7contactform"83
5 - 1$
2013 Intel Corporation.
Fast Track to Intel XDK New
77% After the code that you inserted in the prior step, invo,e form%validate
and configure the following rules:
(ata input for the last+ame field is re>uired
(ata input for the last+ame field must have between = and =6
characters
(ata input on the first+ame field is re>uired
(ata input on the address field is re>uired
(ata input for the Bipcode field may only be digits
7=% 3eview your code to ensure it appears similar to the following:
init:alidation: function$% #
var form = *$"form+contactform"%)
form.!alidate6/
rules: /
lastName: /
reEuired: true0
ran*elen*th: .$0$:2
10
firstName: /
reEuired: true
10
address: /
reEuired: true
10
Hipcode: /
reEuired: true0
di*its: true
1
1
183
&
7F% 'nside the init;< method of the Contact&orm ob@ect, invo,e the
initValidation;< method%
var !ontact"orm = #
init: function$% #
this/populate(eer"ield$%)
this.initIalidation683
&'
populate(eer"ield: function$% #
// omitted for brevity
&'
init:alidation: function$% #
// omitted for brevity
&
&
5 - 1%
2013 Intel Corporation.
Creating Inpt For!s
%rogrammaticall" 1aliate the Form
75% (efine an additional method of the Contact&orm class named
su2$itFor$89
74% 'nside the submit&orm;< method, e-ecute the validation rules that you
defined in step J and output the number of errors to an alert bo-% ?our
code should appear similar to the following:
submitCorm: function68 /
!ar !alidator = 56"form7contactform"8.!alidate683
!alidator.form683
alert6!alidator.numberGf>n!alids6883
1
7G% !ave the file
.ink the #ave button to the submitForm (etho
7H% 8pen contactfor$"ht$l in (esign mode%
7I% Clic, on the button to the right of the Friends with 6eer header and
configure the following property:
id: btn!ave
7J% !ave the file%
=6% 3eturn to inde-%html in Code view%
=7% 'nside the init;< method of the Contact&orm ob@ect, define a tap event
handler for the save button that invo,es the submit&orm method% ?our
code should appear similar to the following:
init: function$% #
this/initiali9ed=true)
this/populate(eer"ield$%)
this/init:alidation$%)
!ar me = this3
56"7btn-a!e"8.bind6"tap"0 function6e8 /
me.submitCorm683
183
&
==% !ave the file and test the app in the emulator% Clic,ing the sa!e button
should trigger the display of the error validation messages%
Theme the &rror (essages
=F% 3eturn to inde-%html in Code mode%
=5% Add the following style definition to the <style> bloc, on line 75%
label.error /
float: left3
color: red3
paddin*-top: .Aem3
!ertical-ali*n: top3
font-&ei*ht:bold
1
5 - 1&
2013 Intel Corporation.
Fast Track to Intel XDK New
=4% !ave the file and re-test the app in the emulator% ?ou should see that
your error messages are now formatted%
N 0nd of "al,through --
5 - 20
2013 Intel Corporation.
Creating Inpt For!s
%ersisting Form )ata
ransactional C32( interfaces re>uire that you support four ma@or
functions:
Create new records
-ead and display records
:pdate pre-e-isting records
Delete records
'n order to update pre-e-isting records, you:ll typically need to populate a
form with data, allow the user to edit the record, and then post it bac, to
the server%
)"namicall" #etting Form Fiel 1alues
o programmatically set the value of an input field, invo,e the field:s %val;<
method as illustrated below:
56"7firstName"8.!al6"-te!e"83
o programmatically set the value of other types of 9#1 form controls,
you must first manipulate the native control and then use the widget:s
refresh method to synchroniBe the enhanced control with its native html
counterpart as illustrated by the following e-amples:
// updatin* chec@bo,es
!ar my(hec@bo, = 56"input.type=9chec@bo,927chec@""8
my(hec@bo,.prop6"chec@ed"0true8.chec@bo,radio6"refresh"83
// updatin* radio buttons
!ar my)% = 56"input.type=9radio927rb""8
my)%.prop6"chec@ed"0true8.chec@bo,radio6"refresh"83
// select controls
!ar myselect = 56"select7beerid"83
myselect.selected>nde, = "3
myselect.selectmenu6"refresh"83
)"namicall" 6etting !ll Form Fiel 1alues
he form%serialiBeArray;< method creates a 9ava!cript array of ob@ects
consisting of your form field names and their associated input values%
!ar formJata = 56"form7contactform"8.serialiHe#rray683
5 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
%osting )ata to an !pplication #erver
'n @#uery 1obile, form submissions are automatically handled using A@a-
whenever possible, resulting in a smooth transition between the form and
the result page% 'f left unspecified, a form:s method will default to get and
its action will default to the current page:s relative path
;Q%mobile%path%get;<<
+ote that forms accept attributes for transitions @ust li,e anchors, so you
can attach a datatransition="pop" and data
direction="reverse"%
'f you do not want a page transition to occur or simply want more control
over the submission process, you:ll need to invo,e the Q%a@a-;< method as
illustrated by the following e-ample:
submitCorm: function68 /
!ar form = 56"form7contactform"83
!ar !alidator = form.!alidate683
!alidator.form683
if 6!alidator.numberGf>n!alids68 == :8 /
5.aDa,6/
type: ";G-"0
url: "http://&&&.,d@trainin*.com/sa!econtact.cfm"0
data: form.serialiHe680
success: function6data8 /
alert6")ecord -a!ed"83
10
error: function6?4LFttp)eEuest0 te,t-tatus0 err8/
!ar ms* = 99.concat6
9status:90 ?4LFttp)eEuest.status0 9Kn90
9status te,t: 90 ?4LFttp)eEuest.statuse,t
83
alert6ms*83
1
183
1
1
+ote the following from the preceding e-ample:
Call the form%serialiBe;< method to retrieve all form field values and
serialiBe them into a single encoded string for posting to the app server%
?ou should always include a failure handler in your A9A) transactions
5 - 22
2013 Intel Corporation.
Creating Inpt For!s
Walkthrough 5*7: Inserting an Upating 2ecors
'n this wal,through you will add data
input validation rules to the contact
form%
'nsert contact records into the
"eb!#$ database
!et the values of form fields
2pdate contact records in the
"eb!#$ database
Programmatically load pages
#teps
Open the %roject
7% 8pen 'ntel )(* +ew
=% Clic, on the word P-&./CT' in the top-left corner of the .2'%
F% Clic, the &pen a Pro*ect button%
5% !elect the following file:
/ft>ntel?d@Ne&/&al@/&al@AB'/&al@AB'.,d@
! )isable .at8.ng Fiels to the Form
4% 8pen contactform%html in (esign mode%
G% (rag an 'nput widget from the Controls > &orm palette and drop it
directly underneath the beers select bo- on the design canvas%
H% Configure the following properties:
$abel: $at ;unchec,ed<
Placeholder: $atitude
+ame: lat
id: lat
I% (rag an 'nput widget from the Controls > &orm palette and drop it
directly underneath the beers select bo- on the design canvas%
J% Configure the following properties:
$abel: $ng ;unchec,ed<
Placeholder: $ongitude
+ame: lng
id: lng
76% .o to code mode and add a disabled property to the lat and lng fields%
5 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
Create a 'ew 2ecor
77% 8pen the index"ht$l file in Code mode%
7=% 3efactor the Contact&orm%submit&orm;< method as indicated below:
submitCorm: function68 /
!ar form = 56"form7contactform"83
!ar !alidator = form.!alidate683
!alidator.form683
if 6!alidator.numberGf>n!alids68 == :8 /
1 else /
alert6">n!alid data input"83
1
1
7F% 'nside the if;< bloc,, use the form%serialiBeArray;< method to serialiBe
all of the form fields into a local variable named fields%
!ar fields = form.serialiHe#rray683
75% 'mmediately after the code that you inserted in the last step, append the
values of the disabled lat and lng fields to the fields array%
fields.fields.len*th2 = /
name: 9lat90
!alue: 5697lat98.!al68
13
fields.fields.len*th2 = /
name: 9ln*90
!alue: 5697ln*98.!al68
13
74% 'mmediately after the code that you inserted in the last step, invo,e the
&riends"ithDeer(D%write3ecord;< method to transfer the data from
the fields variable into your web!#$ database%
CriendsLith%eerJ%.&rite)ecord6
9friend90
this.friend>d0
fields0
function68 /
1
83
7G% 'nside the write-ecord89 callbac, function, use the alert89 method to
output a message to the user and then reload the contacts%html page%
5 - 2"
2013 Intel Corporation.
Creating Inpt For!s
7H% 3eview your su2$itFor$89 method to ensure that it appears similar to
the following:
if $validator/number4f,nvalids$% == -% #
var fields = form/seriali9e.rray$%)
fields;fields/len0th< = #
name: =lat='
value: *$=+lat=%/val$%
&)
fields;fields/len0th< = #
name: =ln0='
value: *$=+ln0=%/val$%
&)
"riends>ith(eer?(/write@ecord$
=friend='
this/friend,d'
fields'
function$% #
alert6")ecord -a!ed"83
5.mobile.chan*e;a*e69friends.html983
&
%)
&
&
7I% !ave the file and test the application in the emulator% ?ou should now
be able to create new contact recordsR
!ttach a tap event listener to the .ist Items in the
Friens .ist
7J% 'n the &riends$ist%display$ist;< method, where indicated by the
comment, attach a tap event listener to the list items%
5697friendsList > li98.bind69tap90 function6e8 /
183
=6% 'nside the event handler, retrieve the numeric identifier in the list item
and transfer its value to the Contact&orm%friend'd property%
*$=+friends7ist > li=%/bind$=tap=' function$e% #
(ontactCorm.friend>d = this.*et#ttribute69data-!alue983
&%)
=7% 'mmediately after the code that you inserted in the prior step,
programmatically change the page to contactform%html
5697friendsList li98.bind69tap90 function6e8 /
!ar (ontactCorm.friend>d = this.*et#ttribute6
9data-!alue983
5.mobile.chan*e;a*e69contactform.html983
183
==% !ave the file and test in the emulator% Clic,ing on an item in the
&riends list should now transfer control to the data entry form%
.oa )ata Into the Form
=F% Add a new method named load-ecord to the ContactFor$ ob@ect%
5 - 25
2013 Intel Corporation.
Fast Track to Intel XDK New
=5% 'nside the load-ecord;< method, define an if89 bloc, that evaluates
whether the value of the ContactFor$"friendId property is null%
load)ecord: function68 /
if 6this.friend>d == null8 /
1
1
=4% 'nside the if89 bloc,, invo,e the Friends;ith6eerD6"run+uer89
method to retrieve the record from the "eb!#$ friends table where the
friend'd is e>ual to the friend'd stored in the Contact&orm ob@ect%
load@ecord: function$% #
if $this/friend,d A= null% #
!ar sEl = "select M from friend &here id = /:1"3
sEl.format6this.friend>d83
CriendsLith%eerJ%.runNuery6sEl0 function6records8 /
183
&
&
=G% 'nside the run#uery callbac, function, loop through the properties of
the first record that was returned from the database >uery, transferring
the values from the >uery result into the form%
load@ecord: function$% #
if $this/friend,d A= null% #
var s2l = "select B from friend where id = #-&")
s2l/format$this/friend,d%)
"riends>ith(eer?(/runCuery$s2l' function$records% #
!ar rec = records.:23
for 6!ar i in rec8 /
56"7" < i8.!al6rec.i283
1
&%)
&
&
=H% 'mmediately after the for-loop that you entered in the prior step, refresh
the beer'd select menu%
56"7beer>d"8.selectmenu6"refresh"0 true83
Invoke the loa2ecor9: metho
=I% 'nside the Contact&orm%init;< method, invo,e the
Contact&orm%load3ecord;< method%
init: function$% #
this/initiali9ed=true)
this/populate(eer"ield$%)
this/init:alidation$%)
this.load)ecord683
var me = this)
*$"+btn3ave"%/bind$"tap"' function$e% #
me/submit"orm$%)
&%)
&
5 - 2#
2013 Intel Corporation.
Creating Inpt For!s
=J% !ave the file%
F6% est the application% ?ou should now be able to edit e-isting contact
records%
N 0nd of "al,through --
5 - 2$
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit #ummar"
'ntel )(* +ew and @#uery 1obile support all /1$4 form element
types%
@#uery 1obile replaces standard chec,bo-, radio button, and select
field controls with controls that have been optimiBed for a mobile
device%
+ative /1$4 form field validation is not supported by most mobile
browsers%
?ou can easily adapt the @#uery Validation Plugin to wor, with @#uery
mobile%
he @#uery Validation Plugin supports validating basic patterns
including email address, re>uired data input, string length, numeric
input, and more%
?ou can persist data in memory, transmit form information to an
application server, or store it in "eb!#$ or /1$4 local!torage%
5 - 2%
2013 Intel Corporation.
Creating Inpt For!s
Unit 2eview
7% he name and id properties of an input field should always be identical
;truePfalse<
=% "hich method do you invo,e in order to get the value of a form fieldS
F% "hich method do you invo,e in order to set the value of a form fieldS
5% ?ou must call the refresh method of a te-t input field after changing its
value ;truePfalse<
4% "hich method can you invo,e to easily combine the values from all of
your form fields in order to transmit them to a serverS
G% "hat are the relative advantagesPdisadvantages to storing information
locally in "eb!#$ instead of posting it to an application serverS
H% (escribe how to populate a <select> control with options that are read
dynamically from an application server%
5 - 2&
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 6:
Adding GEO Features
Unit Objectives
After completing this unit, you should be able to:
Load the Google API
Instantiate a map
Programmatically geocode an address from data input by the user
Programmatically center a map and understand the basic Google map
configuration options
Add overlays to a map
Unit Topics
Getting Started with Google Maps
eploying a Simple Map
Programmatically Geocoding Addresses
Adding !verlays and Map Mar"ers
6 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Getting Started with Google Maps
#he Google Maps $avascript API is a free service that lets you embed
Google Maps in your own web pages% &ersion ' of the API was
specifically designed to support mobile devices as well as traditional
des"top browser applications% It includes a number of utilities for
manipulating maps and adding content to the map through a variety of
collateral services%
#o facilitate the integration of Google Maps into a ()M*based app, use the
Google Maps v' plug*in for ()uery and ()M, available at
http:++code%google%com+p+(,uery*ui*map+%
or!ing with the Google Maps "avascript A#$
#he Google Maps $avascript API &' now comes in three different
versions% All versions support the same features, however, they are limited
in the number of re,uests that they will process during a -.*hour period%
In the current model each of these API versions is limited to a number of
Page &iews a day and a ma/ number of ,ueries per second 0)PS1% Google
considers a 2Page &iew3 to be an instance of the Maps $avascript API
being loaded in the browser or a single re,uest for a static map% It is
important to note that the API contains many different web services and
that ma"ing re,uest to those collateral services 0e%g% the Google Geocoding
service1 will also count against your Page &iew limit%
Page &iew Limitations for the Google Maps $avascript API &' are as
follows:
4% The Free Version 5 Limited to 4666 Page &iews a day per
individual IP address, across all services
-% Purchased Key Version 5 7sers of the API can purchase an
overall daily Page &iew ,uota, that is not limited by IP address
'% Google Maps for Business API 5 466,666 Page &iews a day per
each different service all different API services:
irections API
istance Matri/ API
8levation API
Geocoding API
Places API
9egardless of whether you use the free or paid*for versions of the API you
will be limited to a ma/imum of 10 queries per second per API% :ou can
purchase more bandwidth on an as*needed basis%
6 - 2
2013 Intel Corporation.
Ain! "#$ Feat%res
Using the #urchased %e& 'ersion o( Google Maps
#he free version of Google Maps v' enables you to load the API using the
following synta/:
<!--- load maps API --->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js
se!sor="#$%$&%$'(#%&'%)A*"#">
</script>
;owever, if you wish to trac" map usage or you need a larger number of
daily Page &iews then utili<ing the Purchased =ey &ersion% API "eys are
tied to both your Google account and the domain name from where your
application will be hosted% #he process to obtain an API "ey can be found
at the following 79L:
https:++developers%google%com+maps+documentation+(avascript+tutorial>api?
"ey
As noted in the instructions, you are allowed to use the key from any
domain, but it is strongly encouraged to restrict the usage from the
domain(s) you manage.
:our Purchased =ey license comes with the following restrictions:
4% -@,666 per Page &iew per day limit on map loads%
-% #he Maps API does not include advertising%
'% :our service must be freely accessible to end users% 9ead terms of use
for details governing this%
.% :ou may not alter or obscure the logos or attribution on the map%
@% Maps should not be used to display illegal activity or reveal personal
information
6 - 3
2013 Intel Corporation.
Fast Track to Intel XDK New
or!ing with the #urchased %e& 'ersion o( Google Maps
Ahen you sign up for a paid API "ey, youBll be prompted to register a new
Pro(ect I% #his allows multiple Google services to be tied to a single
pro(ect+API "ey for trac"ing purposes%
After registering youBll be presented with the following screen which
contains your API "ey%
#a"e the API "ey and in(ect it into the script tag that loads the maps API as
illustrated below:
<!--- load maps API --->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js
+ey=,&('%API%-#,!se"sor=#$%&%'&%()$&'(&*A+#$">
</script>
Cor additional licensing information, please see:
https:++developers%google%com+maps+documentation+(avascript+usage
6 - &
2013 Intel Corporation.
Figure 1: egis!ering a Google Map pro"ec!
Figure #: Genera!ing !he Google Maps API Key
Ain! "#$ Feat%res
)eplo&ing a Si*ple Map
eploy a Google map in your app by completing the following steps:
Load the Maps $avaScript library
Load the plug*in for ()uery and $)M
Position your map on a page
Place a mar"er on your map that identifies a location
+oading the Google Maps A#$
#he following is a simple e/ample of loading the Google Maps $avascript
API &':
<!--- load maps API --->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js
+ey=./0/121.02.334se!sor=)A*"#">
</script>
As e/plained previously, Google Maps $avascript API &' now allows you
to implement a mapping solution without re,uiring an API "ey% If you are
using an API =ey is it important to note the following:
If Maps services are restricted to a specific set of domains, and the
load re,uest if performed from a domain that is D!# in that set,
you will receive errors upon calling any function from the library%
:ou must specific !rue or false for the sensor 79L parameter,
depending on if the device has Geospatial System 0GS1 capabilities
or not% :ou should set this to T$% for mobile apps%%
Cor cases where you are using the Cree &ersion of the Google Maps
$avascript API &', the following call would suffice for most solutions:
<!--- load maps API --->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js
4se!sor=)A*"#">
</script>
6 - '
2013 Intel Corporation.
Fast Track to Intel XDK New
+oading the Google Maps ', plugin (or j-uer& and "-M
#he Google Maps &' plug*in for ()uery and $)M is a very fle/ible, highly
customi<able, lightweight 0'%-"E or '%F"E for the full1 library !ne of its
best features is that you can populate a map from microformats, 9Ca or
micro*data on your site, which can be used as a fallbac" if a user doesnBt
have $avascript enabled%
#he plug*in is well*documented and acts as an abstraction library for the
most commonly used functionality available from Google Maps% #he
()uery Google Maps plug*in documentation integrates lin"s to Google
Maps $avascript &' APIs, classes and methods, shortening the learning
curve for including Google Maps in a mobile web app%
#he Google Maps &' plug*in for ()uery and $)M comes with a variety of
libraries, in both full source and minified versions% epending on your
implementation you may use one or more of these:
"query&ui&'ap&"s 5 Main library file
"query&ui&'ap&e(!ensions&"s 5 7sed with Geocoding
"query&ui&'ap&'icroda!a&"s 5 7sed for microdata
implementations
"query&ui&'ap&'icrofor'a!&"s 5 7sed with microformats
"query&ui&'ap&o)erlays&"s 5 7sed with shapes and =ML
"query&ui&'ap&rdfa&"s 5 7sed with 9Ca data
"query&ui&'ap&ser)ices&"s 5 7sed with irections and Street view
8ach of these libraries has an associated minified version for you to wor"
with% Ahen implementing for $)M you will use a special minified version
of the main library file "query&ui&'ap&full&'in&"s%
#o handle the most basic of map implementations your to implement the
plug*in will loo" li"e the following:
<!--- 5oogle 6aps / 789ery Pl9gi! --->
<script type="text/javascript"
src="9i/j:9ery.9i.map.;9ll.mi!.js">
</script>
6 - 6
2013 Intel Corporation.
Ain! "#$ Feat%res
#lacing &our *ap on a page
:ou can instantiate a map into any ;#ML element that has a uni,ue
identifier 0typically a GdivH1% #he map will conform to the defined si<e of
the container% A typical map container would resemble the following:
<div id="map%ca!vas"></div>
In order to style the map you will either provide in*line styles for the
GdivH tag or provide some parameters for the div to constrain the si<e% In
this e/ample, you could include a GstyleH bloc" at the top of the file, or
place the style within a ISS file% #he entry for the I Bmap?canvasB could
loo" li"e this:
<style type="text/css">
html , height: -../ 0
1ody , height: -../2 margi": .2 paddi"g: . 0
<map%ca!vas = >idth: ?@@AB height: .1@px C
</style>
Ahen implementing for mobile you will want pay particular attention to
the map canvas parameters% epending on how the styles have been
implemented with the application you may have to push the map into a
fi/ed height%
Instantiating a map with the $)M Google Maps plugin typically re,uires
you to call a constructor named g'ap*+ as illustrated below% Dote the use
of ,'ap-can)as which is used to point the map to our 2map?canvas3
GdivH and the use of the 'ap.p!ions variable to set some basic
parameters for the map,%
<!-- loadi!g a 5oogle 6ap 9si!g j89ery -->
<script type="text/javascript">
var map&ptio!s = =
Dce!terD: D.1.E13@@@@@@F -03.E/@?.?@@@DF
DGoomD: ?HF
disaIleJe;a9lt(I: ;alse
CB
KLD<map%ca!vasDM.gmapL=
ce!ter: map&ptio!s.ce!terF
map$ypeId: google.maps.6ap$ypeId."A$#**I$#F
Goom: map&ptio!s.GoomF
disaIleJe;a9lt(I: map&ptio!s.disaIleJe;a9lt(I
CMB
</script>
6 - (
2013 Intel Corporation.
Fast Track to Intel XDK New
Setting Options (or &our Map
#he Google Maps $avascript API Map class supports over '6 different
configuration properties, generally referred to as Map.p!ions& A full
listing can be found here:
https:++developers%google%com+maps+documentation+(avascript+reference>M
ap!ptions
At a minimum, the following options must be included when instantiating
a new Map ob(ect:
/oo' 0type int1 5 ma/ <oom value is 4F
'apTypeId 5 indicates the type of map to display
cen!er 5 center point on the map, in
Latitude+Longitude
.e(reshing the Map
In some user*cases, as illustrated by Cigure ', your
map may only partially instantiate% #o handle this
glitch, invo"e the gmap refresh01 method after a brief
delay to allow the map to initiali<e%
var loc = "e3 google.maps.+at+"g4
"56.7.6878"9 "-::..58;<:"=2
>map?o"tai"er.gmap4,
ce"ter: loc9
@oom: -89
map%ypeId:google.maps.Aap%ypeId.#A%$++I%$
0=2
set$imeo9tL"KLD<mapDM.gmapLDre;reshDM"FH@@MB
6 - )
2013 Intel Corporation.
Figure 0: Par!ially
rendered 'ap&
Ain! "#$ Feat%res
Geocoding a starting position
!ne of the most important Map.p!ions is the the cen!er option% #his
option gives the map its starting center latitude and longitude coordinates%
:ou can manually geocode a starting address by going to http:++geocoder%us
Using )i((erent Map T&pes
!ne of the main features of Google Maps are the different map types% In
the e/ample below we used a Map!ption called MapTypeI1 to name of
the map type displayed% #hese are defined in the Google API
documentation as follows:
.A1MAP 0efault1 * displays the normal, default - tiles of
Google Maps%
2AT%33IT% * displays photographic tiles%
45BI1 * displays a mi/ of photographic tiles and a tile layer for
prominent features 0roads, city names1%
T%AI6 * displays physical relief tiles for displaying elevation and
water features 0mountains, rivers, etc%1%
#he value of the map type is case sensitive and coincides with the different
map types you can choose from the standard maps 7I%
<!-- I!sta!tiati!g a map 9si!g the "atellite 6ap type -->
KLD<map%ca!vasDM.gmapL=
Dce!terD: map&ptio!s.ce!terF
Dmap$ypeIdD: google.maps.6ap$ypeId."A$#**I$#F
DGoomD: map&ptio!s.GoomF
DdisaIleJe;a9lt(ID: map&ptio!s.disaIleJe;a9lt(I
CMB
6 - *
2013 Intel Corporation.
Figure 7: Manually con)er! s!ree! addresses !o la!8lng posi!ions
Fast Track to Intel XDK New
/usto*i0ing the loo!1(eel o( a *ap
Another set of commonly used Map!ptions are the controls% Google Maps
allows you to customi<e the various controls within your maps% In our
e/ample on the previous page we set the disa9le1efaul!$I option to false%
#his enables the <oom, map type, and street view controls by default%
!ther supported controls, which allow you more granularity, include the
following:
Proper!y 1escrip!ion
street&iewIontrol Eoolean% #he initial enabled+disabled state of the
Street &iew control% #his control is part of the
default 7I, and should be set to false when
displaying a map type on which the Street &iew
road overlay should not appear 0e%g% a non*8arth
map type1%
panIontrol Eoolean% #he enabled+disabled state of the Pan
control%
scaleIontrol Eoolean% #he initial enabled+disabled state of the
Scale control%
map#ypeIontrol Eoolean% Euttons that let the user toggle between
map types 0such as Map and Satellite1% #here are
several levels of sub options for controlling the
position and style if the map type controls that can
be defined here%
overviewMapIontrol Eoolean% A collapsible overview map in the corner
of the screen
6 - 10
2013 Intel Corporation.
Ain! "#$ Feat%res
al!through 623: Getting Started with Maps
In this wal"through you will manually geocode
an address and center a map on that location
using the $)M Plug*in and Google Maps
$avascript API &'%
Steps
Open the #roject
4% !pen Intel J= Dew
-% Ilic" on the word P.:%;T2 in the top*
left corner of the G7I%
'% Ilic" the .pen a Pro"ec! button%
.% Select the following file:
/;tI!telNd+Oe>/>al+/>al+3%?/>al+3%?.xd+
Manuall& Geocode a +ocation
@% !pen a web browser to http:++geocoder%us
K% 8nter your address and clic" search%
L% Dote the latitude and longitude of your address%
+oad Google Maps and the Google "-M Maps #lugin
M% !pen inde/%html in code view%
F% Ahere indicated by the comment, insert the script declarations to
initiali<e the Google Maps $avacript API &' library% :our code should
resemble the following:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js
se!sor=tr9eP></script>
46% After the code that you inserted in the prior step, add a GscriptH tag
that loads the ()uery Google Map plugin%
<script type="text/javascript"
src="js/j:9ery.9i.map.js"></script>
.eserve a Space (or the Map
44% !pen contactdetail%html in esign mode%
4-% Crom the Iontrols H Layout palette, drag a 9!A widget and drop it
onto the middle of the esign Ianvas
6 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
4'% Crom the Iontrols H Layout palette, drag a 9!A widget and drop it
directly underneath the row that you inserted in the prior step%
4.% Go to Iode view%
4@% Locate the mar"up that was generated for the second row widget and
add an id property with a value of 2map3 as illustrated below:
<div class="grid grid-pad Bro3 Bi1&ro3&< ro3-height-<"
data-Bi1="layoBt/ro3"
id="map">
4K% Save the file%
.ender the Map
4L% !pen inde/%html in code view% Dote that a Iontactetail ob(ect has
been defined for you%
4M% Inside the Iontactetail ob(ect, define an init01 method%
4F% Inside the init01 method, define a local variable named NmapIontainer
that points to the map row that you defined in step 4@%
var KmapQo!tai!er = KL"<map"MB
-6% After the code that you inserted in the previous step, use the gmap01
method to instantiate a map thatBs centered on the lat+lng position that
you noted from step L%
-4% 9eview your code to ensure that it appears similar to the following:
var Qo!tactJetail = =
;rie!dId: !9llF
g6ap: !9llF
i!it: ;9!ctio!LM =
var KmapQo!tai!er = KL"<map"MB
this.g6ap = KmapQo!tai!er.gmapL=
ce!ter: !e> google.maps.*at*!g L".1.E@13E3"F
"-00.@.3H20"MF
Goom: ?3
CMB
C
C
--% Save the file%
$nvo!e the /ontact)etail #age
-'% In the Iontacts%displayList01 method, modify the tap event listener for
the friendsList list items to load the contactetail%html page% :our code
should appear as follows:
>4CDErie"ds+ist liC=.1i"d4CtapC9 EB"ctio"4e= ,
?o"tact*orm.Erie"dId = this.getAttri1Bte4Cdata-valBeC=2
Qo!tactJetail.;rie!dId = Qo!tact)orm.;rie!dIdB
K.moIile.cha!gePageLDco!tactdetail.htmlDMB
0=2
-.% Save the file and test% #apping on a list item should display a small
sliver map on the Iontactetail page%
6 - 12
2013 Intel Corporation.
Ain! "#$ Feat%res
Adjust Map .endering
-@% 9eturn to inde/%html in I!8 mode%
-K% At the bottom of the Iontactetail%init01 method, use ()uery to set the
height of the map to be the height of the document body minus '66
pi/els 0to account for the header, footer, and top row1%
KmapQo!tai!er.height LKL"Iody"M.heightLM - 2@@MB
-L% Save the file and test in the 8mulator% :ou should see a larger map,
however that still doesnBt ,uite render correctly%
-M% 9eturn to inde/%html in I!8 mode%
-F% At the bottom of the Iontactetail%init01 method, insert a set#imeout01
method that refreshes the map after @66 milliseconds%
set$imeo9tL"KLD<mapDM.gmapLDre;reshDM"FH@@MB
'6% Save the file and test the application in the emulator%
5 8nd of Aal"through **
6 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
#rogra**aticall& Geocoding Addresses
In order to plot a position on a map, you must "now its geocode, or
latitude+longitude% :ou can programmatically determine the geocode of an
address by using the geocode*+ method of the google&'aps&Geocoder
ob(ect% Dote the following:
#he use of the geocode*+ method is restricted daily based on your
Google Maps API license levels%
Cor best results, store geocodes of specific locations in your
database% Dote that GoogleBs license terms specifically forbid
storing positions generated by GoogleBs geocoder in a database%
Ahen calling the geocode*+ method, you must specify a callbac"
function that will receive the calculated coordinates
#he geocode*+ method is called asynchronously% As such you will
not be able to pass variables out of the callbac" function% If you
need to pass the coded data out you will need to chain your
functions together%
#he latitude+longitude is returned within a geometry structure
within a results array% :ou can access the information by calling
the lat01 and lng01 methods%%
In the following e/ample illustrates Geocoding and address and storing the
resulting lat+long into a variable% #he map is then centered on the specified
position%
<!-- get lat a!d l!g o; address -->
var geocoder = !e> google.maps.5eocoderLMB
geocoder.geocodeL
=
address : D?3@@ Pe!!sylva!ia Ave Rashi!gto! JQD
CF
;9!ctio!Lres9ltsF stat9sM =
var locatio!B
i;Lstat9s != google.maps.5eocoder"tat9s.&-M =
alertL"Address !ot ;o9!d"MB
C else =
locatio! = res9ltsS@T.geometry.locatio!B
C
KLD<map%ca!vasDM.gmapL=
ce!ter: locatio!F
Goom: ?HF
disaIleJe;a9lt(I: ;alse
CMB
CMB
6 - 1&
2013 Intel Corporation.
Ain! "#$ Feat%res
al!through 624: Geocoding Addresses
In this wal"through you will programmatically
geocode your contactBs address%
efine disabled input fields
Attach event listeners to form fields
Geocode a street address
Steps
Open the #roject
4% !pen Intel J= Dew
-% Ilic" on the word P.:%;T2 in the top*left corner of the G7I%
'% Ilic" the .pen a Pro"ec! button%
.% Select the following file:
/;tI!telNd+Oe>/>al+/>al+3%2/>al+3%2.xd+
Add 5uttons to the /ontact)etail #age
@% !pen contactdetail%html in esign mode%
K% Add a 2bac"3 button to the page header by dragging a Eutton widget
from the Iontrols H Corms panel and dropping it on the leftmost
position of the header toolbar%
L% Ionfigure the following Eutton properties:
Label: Eac" 0unchec"ed1
Icon: ui*icon*bac" 0chec"ed1
Icon Position: icon only
M% Go into code view and add the following property to the 2Eac"3
button:
data-rel="Iac+"
F% 9eturn to esign mode%
46% Add an 28dit3 button to the page header by dragging a Eutton widget
from the Iontrols H Corms panel and dropping it on the right*most
position of the header toolbar%
44% Ionfigure the following Eutton properties:
Label: 8dit 0unchec"ed1
Icon: ui*icon*edit 0chec"ed1
Icon Position: icon only
6 - 1'
2013 Intel Corporation.
Fast Track to Intel XDK New
Geocode the Address
4-% Go to code view and add the following property to the edit buttonBs
anchor tag:
hrefO3contactform%html3
4'% Save the file and test the application in your emulator%
Geocode the Address
4.% !pen inde/%html in Iode mode%
4@% Add a method to the IontactCorm ob(ect named geoIode%
4K% Inside the geoIode function, create a variable named geocoder that
instantiates the Google Maps Geocoder ob(ect%
var geocoder = !e> google.maps.5eocoderLMB
4L% irectly under the code that you inserted from the prior step, call the
geocoder%Geocode method, passing it the address and <ip code that the
user entered in the form%
geo?ode: EB"ctio"4= ,
var geocoder = "e3 google.maps.Feocoder4=2
geocoder.geocodeL=
address : KLD<addressDM.valLM U " " U KLD<GipcodeDM.valLM
CF ;9!ctio!Lres9ltsFstat9sM =
CMB
0
4M% Inside the geocoder callbac" function, insert code to populate the lat
and lng te/t fields with the resulting geocode data% If the geocding
failed, set the values of the lat and lng field to the empty string% :our
code should appear similar to the following:
geoQode: ;9!ctio!LM =
var geocoder = !e> google.maps.5eocoderLMB
geocoder.geocodeL=
address : KLD<addressDM.valLM U " " U KLD<GipcodeDM.valLM
CF ;9!ctio!Lres9ltsFstat9sM =
i;Lstat9s != google.maps.5eocoder"tat9s.&-M =
alertL"Address !ot ;o9!d"MB
KL"<lat"M.valLDDMB
KL"<l!g"M.valLDDMB
C else =
KL"<lat"M.valLres9ltsS@T.geometry.locatio!.latLMMB
KL"<l!g"M.valLres9ltsS@T.geometry.locatio!.l!gLMMB
C
CMB
C
6 - 16
2013 Intel Corporation.
Ain! "#$ Feat%res
Attach Event +isteners to the Address and 6ip/ode
Fields
4F% At the bottom of the IontactCorm%init01 method, create event listeners
for the change event on the address and <ipcode fields that fire the
geocode method%
KL"<address"M.Ii!dL"cha!ge"F this.geoQodeMB
KL"<Gipcode"M.Ii!dL"cha!ge"F this.geoQodeMB
-6% Save the file and test the app in the 8mulator% 8diting a contact record
should cause the address to be geocoded with the results getting placed
into the lat+lng input fields%
** 8nd of Aal"through **
6 - 1(
2013 Intel Corporation.
Fast Track to Intel XDK New
Adding Overla&s and Map Mar!ers
!verlays are map ob(ects that indicate points, lines, areas, or ob(ects which
are tied to specific lat+lng coordinates% #here are a number of 2canned3
overlays, such as the Google Maps #raffic Layer, that you can easily add to
your map% Map mar"ers, identifying specific positions on your map, are a
form of custom overlay%
Using Overla&s
Google Maps enables you to add transparency layers to your map that
visuali<e the following datasets:
3ayer 1escrip!ion
=mlLayer 9enders =ML and Geo9SS elements into a Maps
API &' tile overlay%
;eatmapLayer 9enders geographic data using a ;eatmap
visuali<ation
Cusion#ablesLayer 9enders data contained in Google Cusion #ables%
#rafficLayer 9enders a layer depicting traffic conditions and
overlays representing traffic%
#ransitLayer isplays the public transport networ" of your city
on the map%
AeatherLayer and
IloudLayer
Allow you to add weather forecasts and cloud
imagery to your map%
EicyclingLayer 9enders a layer of bi"e paths and+or bicycle*
specific overlays into a common layer% #his layer is
returned by default within the irections9enderer
when re,uesting directions of travel mode
EII:ILIDG%
PanoramioLayer Adds photos from Panoramio as a layer%
emographicsLayer 9enders 7nited States demographic information as
a layer, and is available to Google Maps API for
Eusiness customers only% It is contained within the
visuali<ationlibrary%
6 - 1)
2013 Intel Corporation.
Ain! "#$ Feat%res
)ispla&ing the /urrent Tra((ic /onditions
Instantiate the traffic layer using the google%maps%#rafficLayer01
constructor% In order to apply it to a map, you must call the setMap01
method of the resulting ob(ect%
#he following code snippet illustrates how to add traffic map overlay to a
Google Map% Dote that the use of the callbac" method which receives a
pointer to the google map instance created by the ()uery Maps plugin%
var >map?o"tai"er = >4"Dmap"=2
>map?o"tai"er.gmap4,
ce"ter: "e3 google.maps.+at+"g 4"56.7.6878"9 "-::..58;<:"=9
@oom: -89
callIac+: ;9!ctio!LmapM =
var tra;;ic*ayer = !e> google.maps.$ra;;ic*ayerLMB
tra;;ic*ayer.set6apLmapMB
C
0=2
)ispla&ing the #anora*io +a&er
Loading the Panoramio layer re,uires you to modify the url of the GscriptH
tag that loads the Google Maps API as illustrated by the following
e/ample:
<script
src="https://maps.googleapis.com/maps/api/js
v=5.exp!se"sor=trBe!liIraries=pa!oramio">
</script>
Aith the Panoramio version of the Google Maps API loaded, it becomes a
simple matter to instantiate the map with local photos:
var >map?o"tai"er = >4"Dmap"=2
>map?o"tai"er.gmap4,
ce"ter: "e3 google.maps.+at+"g 4"56.7.6878"9 "-::..58;<:"=9
@oom: -89
call1acG: EB"ctio"4map= ,
var traEEic+ayer = "e3 google.maps.%raEEic+ayer4=2
traEEic+ayer.setAap4map=2
var pl = !e> google.maps.pa!oramio.Pa!oramio*ayerLMB
pl.set6apLmapMB
0
0=2
6 - 1*
2013 Intel Corporation.
Fast Track to Intel XDK New
Adding Map Mar!ers
Mar"ers identify points on a map and inherit from the same base class as
overlays% #hey are assigned a position on a map, and can be assigned a
number of properties, including tooltips and custom icons for display%
7sing the Google Maps plug*in for ()uery and $)M you can add a mar"er
to an e/isting map with the following bloc" of code:
KLD<map%ca!vasDM.gmapLDadd6ar+erDF =
positio!: D/2../HH0.F-0?.@E1.23DF
Io9!ds: ;alse
CMB
Dote the following:
#he positio" attribute determines where the mar"er should be placed
on the map%
#he 1oB"ds attribute identifies whether or not you want the map to
automatically <oom in on the mar"er when the mar"er is instantiated%
Adding a Mar!er to the /enter o( the Map
In most use*cases, youBll want to place a ma"er on the map to identify the
center point% As illustrated by the following code snippet, you can easily
implement this in the callbac" handler that e/ecutes during the map
instantiation process%
var >map?o"tai"er = >4"Dmap"=2
>map?o"tai"er.gmap4,
ce"ter: "e3 google.maps.+at+"g 4"56.7.6878"9 "-::..58;<:"=9
@oom: -89
call1acG: EB"ctio"4map= ,
var traEEic+ayer = "e3 google.maps.%raEEic+ayer4=2
traEEic+ayer.setAap4map=2
var pl = "e3 google.maps.pa"oramio.Pa"oramio+ayer4=2
pl.setAap4map=2
this.add6ar+erL=
positio!: map.getQe!terLM
CM
0
0=2
6 - 20
2013 Intel Corporation.
Ain! "#$ Feat%res
al!through 62,: )e(ining Mar!ers
In this wal"through you will change your
map instantiation to center the map on your
friendBs location and display a map mar"er%
9etrieve data from a AebS)L database
Ienter the map on a lat+lng position that
was saved to a AebS)L database
Add a mar"er to the map
Steps
Open the #roject
4% !pen Intel J= Dew
-% Ilic" on the word P.:%;T2 in the
top*left corner of the G7I%
'% Ilic" the .pen a Pro"ec! button%
.% Select the following file:
/;tI!telNd+Oe>/>al+/>al+3%./>al+3%..xd+
.etrieve and /ache /ontact $n(or*ation (ro* ebS-+
@% Add the following properties to the Iontactetail ob(ect:
contactata
mapIenter
K% Inside the init01 method, define a local variable named me and set it
e,ual to the Iontactata ob(ect%
var me = thisB
L% At the end of the ini!*+ method, use AebS)L to retrieve the
information for the friend whose primary "ey value is stored in the
Iontactetail%friendId property%
)rie!dsRithVeerJV.r9!89eryL
"select W ;rom ;rie!d >here id = " U this.;rie!dIdF
;9!ctio!LrecordsM =
C
MB
M% Inside the AebS)L callbac" function, set the
Iontactetail%contactata property e,ual to the record that was
returned from the s,l ,uery%
me.co!tactJata = recordsS@TB
6 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
F% After the code that you inserted in the prior wal"through, set the
Iontactetail%mapIenter property e,ual to the a Google LatLng ob(ect
thatBs set to the lat+lng position retrieved from the database ,uery%
me.mapQe!ter = !e> google.maps.*at*!g L
recordsS@T.latF recordsS@T.l!g
MB
46% Invo"e the initMap01 method from the AebS)L function callbac"%
/enter the Map and Add Overla&s
44% Inside the Iontactetail%initMap01 method, configure the map instance
to center on Iontactetail%mapIenter%
this.gAap = >map?o"tai"er.gmap4,
ce"ter: this.mapQe!terF
@oom: -8
0=2
4-% Inside the NmapIontainer%gmap01 configuration ob(ect, add a callbac"
method%
this.gAap = >map?o"tai"er.gmap4,
ce"ter: this.map?e"ter9
@oom: -89
call1acG: EB"ctio"4map= ,
0
0=2
4'% Inside the callbac" function, instantiate the traffic and panoramio
layers and apply them to the map%
this.gAap = >map?o"tai"er.gmap4,
ce"ter: this.map?e"ter9
@oom: -89
call1acG: EB"ctio"4map= ,
var tra;;ic*ayer = !e> google.maps.$ra;;ic*ayerLMB
tra;;ic*ayer.set6apLmapMB
var pa!oramio*ayer = !e>
google.maps.pa!oramio.Pa!oramio*ayerLMB
pa!oramio*ayer.set6apLmapMB
C
0=2
6 - 22
2013 Intel Corporation.
Ain! "#$ Feat%res
Add a Mar!er to the Map
4.% At the bottom of the map instance callbac" function, add a map mar"er
to the center of the map%
this.gAap = >map?o"tai"er.gmap4,
ce"ter: this.map?e"ter9
@oom: -89
call1acG: EB"ctio"4map= ,
me.map = map2
var traEEic+ayer = "e3 google.maps.%raEEic+ayer4=2
traEEic+ayer.setAap4map=2
var pa"oramio+ayer = "e3
google.maps.pa"oramio.Pa"oramio+ayer4=2
pa"oramio+ayer.setAap4map=2
this.add6ar+erL=
positio!: map.getQe!terLM
CMB
0
0=2
4@% Save the file and test in the emulator using a 2friend3 record that has
been successfully geocoded%
** 8nd of Aal"through **
6 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Su**ar&
#here are multiple licensing options for the Google Maps $avascript
API &', including a paid for subscription model
7se the $avaScript loader to dynamically load Google APIBs at runtime
#o facilitate using Google Maps with ()uery and $)M you can use the
Google Maps &' plugin for ()uery and ()uery Mobile
7se the google%maps%Map01 ob(ect to instantiate maps on your pages in
basic $avascript
7se N0>map?canvas1%gmap01 to instantiate maps using the plugin for
()uery mobile
7se ()uery to loop through a returned dataset to programmatically
populate a map overlay components%
Ireate map mar"ers using the google%maps%Mar"er01 or addMar"er01
and assign them to overlays
6 - 2&
2013 Intel Corporation.
Ain! "#$ Feat%res
Unit .eview
4% Ahat do you need to get started using the Google Maps APIP
-% escribe the process for placing a map on a web page
'% escribe the steps for geocoding an address
.% Ahat are the types of overlays that you can place on a Google MapP
@% :ou cannot configure the loo" of a map mar"erP 0true+false1
6 - 2'
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 7:
Using Device Features
Unit Objectives
After completing this unit, you should be able to:
Retrieving the device's current location
Programmatically activate the phone dialer
Launch the device's email client with the subject, body, and to: fields
pre-filled
Prompt the user to launch the device's built-in navigation app
reate an event listener for the accelerometer so that an action is
performed when the user sha!es their device"
Listen for push notifications
Unit Topics
Retrieving the #evice's urrent Location
Launching the Phone, $mail, and %avigation Apps
Listening to the Accelerometer
Listening for Push %otifications
7 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Retrieving the Device's Current Location
&se the navigator"geolocation class to retrieve the user's current position
from its 'P( sensor"
Getting the Latitude and Longitude
As illustrated by the following code sample, determining a device's
position is an asynchronous event due to the latency associated with
locating the proper satellites from which to calculate a )fi*)" +hen the
position of the device has been calculated, the callbac! handler will be
e*ecuted"
%ote that you should always provide an error handler as this feature may
fail if the user moves to a location where line-of-sight to the satellites and a
wifi connection are both unavailable"
navigator.geolocation.getCurrentPosition(
function(position) {
var pos = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude);
},
function (error) {
var msg = "";
switc(error.code) {
case error.P!"#$%%$&'()!'$!)*
msg="+ser denied te re,uest for -eolocation."
.rea/;
case error.P&%$0$&'(+'121$L13L!*
msg="Position is unavaila.le."
.rea/;
case error.0$#!&+0*
msg="0e -P% re,uest timed out";
.rea/;
case error.+'4'&5'(!""&"*
msg = "1n un/nown error occurred getting 6our position"
.rea/;
}
alert(msg);
}
);
7 - 2
2013 Intel Corporation.
Usin De!ice Feat"res
Retrieving Additiona !n"or#ation "ro# the G$% %ensor
,n addition to the latitude and longitude, most device browsers will also
return the following information as properties of the position"coords object"
Property Description
accuracy -he accuracy of the position
altitude -he altitude .in meters/ above sea level
altitudeAccuracy -he accuracy of the altitude 0uery
heading -he user's heading, specified in degrees cloc!wise from
%orth
speed -he speed .in meters per second/
timestamp -he date1time of the last successful re0uest
Cacuating Distance to Target
2ou can calculate the distance between two points by using either the
3aversine formula or the (pherical Law of osines" -he following
function represents a 4ava(cript implementation of the 3aversine formula:
var calc)istance = function(lat7,lng7,lat8,lng8) {
var " = 9:;:; << use 9:;: for miles or =9>7 for /m
var dLat = (lat8?lat7) @ #at.P$ < 7AB ;
var dLon = (lng8?lng7)@ #at.P$ < 7AB;
var lat7 = lat7 @ #at.P$ < 7AB;
var lat8 = lat8 @ #at.P$ < 7AB;
var a = #at.sin(dLat<8) @ #at.sin(dLat<8) C
#at.sin(dLon<8) @ #at.sin(dLon<8) @ #at.cos(lat7) @
#at.cos(lat8);
var c = 8 @ #at.atan8(#at.s,rt(a), #at.s,rt(7?a));
return " @ c;
}
7 - 3
2013 Intel Corporation.
Fast Track to Intel XDK New
&nabing $er#issions to Access the G$% %ensor
As illustrated in 5igure 6, you will need to turn on permissions to the 'P(
sensor prior to producing a native build" Android apps that attempt to
access the gps sensor without the proper permissions will fail silently"
7 - #
2013 Intel Corporation.
Figure 1: Configuring GeoLocation Permission
Usin De!ice Feat"res
'a(through 7)*: Getting the Device Location
,n this wal!through you will get the device's
current position and calculate the distance
between the device and your selected friend"
,mplement a multi-column layout
5ormat +eb(7L data using a -emplate
'et the device's current position
alculate range to target
%teps
Open the $roject
6" 8pen ,ntel 9#: %ew
;" lic! on the word PROJECTS in the top-
left corner of the '&,"
<" lic! the Open a Project button"
=" (elect the following file:
<ft$ntelDd/'ew<wal/<wal/>(7<wal/>(7.Ed/
+odi", the Contact Detai La,out
>" 8pen contactdetail"html in #esign mode"
?" 5rom the ontrols @ Layout palette, drag a
olumn widget and drop it to the left of
the top row of page layout"
A" #rag the left column's right-divider to the
right until your layout appears similar to
5igure <"
B" 'o to ode Ciew
D" Add an idEFcontactdetailsF property to the column that you just added"
2our code should resemble the following:
<div class="col uib_col_4 col-0_6-12" data-uib="layout/col">
<div class="widget-container content-area vertical-col"
id="contactdetails">
<span class="uib_si!"></span>
</div>
</div>
6G" (ave the file
7 - $
2013 Intel Corporation.
Figure : Output contact
info an! !istance to
target"
Figure #: ContactDetai$
page $ayout
Fast Track to Intel XDK New
Output Contact !n"or#ation
66" 8pen inde*"html in ode view"
6;" +here indicated by the comment, define a template that contains
placeholders for the contact's first name .HGI/, last name .H6I/, address
.H;I/, and favorite beer .H<I/ as well as a Jspan@ tag from where the
distance will be output"
Fscript t6pe="teEt<template" id="tplContact"G
Fdiv class="contactname"G{B} {7}F<divG
Fdiv class="contactaddress"G{8}F<divG
Fdiv class="contactdistance"G{9} is onl6 Fspan
id="distancetofriend"GF<spanG awa6HF<divG
F<scriptG
6<" #efine a method in the ontact#etail object named output#etails./"
6=" ,nside the output#etails./ method, define a local variable named
tplontact that contains the html from the template that you defined
from step 6;"
var tplContact = I("JtplContact").tml();
6>" After the code that you added in the prior step, define a local variable
named html that processes the contact's information through the
template"
var tml = tplContact.format(
tis.contact)ata.first'ame,
tis.contact)ata.last'ame,
tis.contact)ata.address,
tis.contact)ata..eername
);
6?" After the code that you inserted in the prior step, output the contents of
the html variable to the Kcontactdetails Jdiv@ element"
I("Jcontactdetails").tml(tml);
6A" +here indicated by the comment, invo!e the
ontact#etail"output#etails./ method"
6B" (ave the file and test in the emulator" -apping on a contact name
should now display the contact's name, address, and favorite beer in an
area positioned immediately above the map"
Get the Device's Current $osition
6D" Return to inde*"html in ode mode"
;G" Add an additional method named outputDistance%& to the
ContactDetai$ object"
;6" ,nside the output#istance./ method, define a variable named me that
points to the current scope"
var me = tis;
7 - %
2013 Intel Corporation.
Usin De!ice Feat"res
;;" ,nvo!e the navigator"geolocation"geturrentPosition./ method,
defining success and error callbac! functions" 2our code should
appear similar to the following:
navigator.geolocation.getCurrentPosition(
function(position) {
},
function(error) {
}
);
;<" ,nside the success callbac! function, convert the device's latitude and
longitude coordinates to a google maps lat1lng object and store the
resulting object into the ontact#etail"currentPosition property"
navigator"geolocation"get#urrent$osition%
&unction%position' (
me.currentPosition =
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
)*
&unction%error' (
)
'+
;=" After the code that you inserted in the prior step, define a local variable
named miles that contains the calculated distance between the device
and the selected friend"
%ote: -he ca$cDistance function is defined on line 6G; of inde*"html
var miles = calc)istance(
me.mapCenter.lat(),
me.mapCenter.lng(),
position.coords.latitude,
position.coords.longitude
);
;>" ,mmediately after the code that you inserted in the prior step, output
the value from miles into the Jspan idEFcontactdistanceF@ element"
I("Jdistancetofriend").tml(miles C " miles ");
;?" ,nside the error function callbac!, output an alert./ that indicates that
an error occurred in retrieving the device's coordinates"
;A" +here indicated by the comment inside of the ontact#etail"init./
method, invo!e the output#istance function"
;B" (ave the file and test" -apping on a contact should now display the
distance between the device and the contact's address as illustrated by
the screenshot in 5igure ;"
L $nd of +al!through --
7 - 7
2013 Intel Corporation.
Fast Track to Intel XDK New
Launching the $hone- &#ai- and .avigation Apps
2ou can e*ecute the device's phone dialer, email, and navigation apps by
programmatically setting location"href to a specially encoded url lin! as
illustrated below:
<< launc mail?compose
location.ref=Kmailto*sdruc/erLfigleaf.comK;
Activating the $hone Diaer
&se the tel &RL scheme to launch the device's phone dialer and initiate
dialing of the specified phone number" +hether or not the user is prompted
to dial or the dialing occurs automatically is dependent on the type of
mobile operating system being used"
-he javascript synta* to activate the native Phone app is:
location.ref="tel*;;;?;;;?;;;;";
%ote that the i8( browser will automatically try to detect and hyperlin!
strings that match a phone number pattern" 2ou can disable this behavior
by adding the following meta tag to your html:
Fmeta name = "format?detection" content = "telepone=no"G
Activating the &#ai Cient
&se the mailto: url scheme to launch the mail app's compose feature and
programmatically fill the following fields:
Synta' Description
mailto: Receipient or recipients .comma-separated list/
MccE -he Ncarbon copyF recipients .comma-separated list/
MbccE -he Nblind carbon copyF recipients .comma-separated list/
Msubject -he subject of the email, url encoded using 4ava(cript's
escape./ method"
MbodyE -he body of the message .including line brea!s/, url
encoded using 4avascript's escape./ method"
7 - &
2013 Intel Corporation.
Usin De!ice Feat"res
-o launch the mail client, dynamically assemble the url and
programmatically clic! it as illustrated by the following code snippet:
var mailLin/ = "mailto*{B}Msu.Nect={7}O.od6={8}";
mailLin/ = mailLin/.format(
"sdruc/erLfigleaf.com",
escape("Can $ come over nowM"),
escape("Pe6 good .udd6, can $ come overM")
);
location.ref = mailLin/;
/ranching ,our code "or Turn)b,)Turn Directions
-he techni0ues for launching turn-by-turn directions in i8( and Android
vary significantly, therefore you'll need to branch your code by inspecting
the contents of the navigator"userAgent property as illustrated below:
if( <1ndroid<i.test(navigator.user1gent) ) {
<< android?specific code
} else if (<iPoneQiPadQiPod<i.test(navigator.user1gent)) {
<< ios specific code
}
Activating the .avigation App on iO%
8n i8(, the maps &RL scheme can open the native Apple maps app to
show geographical locations as well as generate driving directions between
two points"
8n i8(, maps lin!s are specified using a special maps:11 uri as illustrated
by the following snippet:
Fa ref="maps*<<Mdaddr=8BBB 4 %t 8BB9=Osaddr=santa clara,
C1"G)irectionsF<aG
2ou can pass the following parameters to the maps"apple"com url:
(rgument Description
0 -his parameter is treated as if it had been typed into the
0uery bo* by the user in the Oaps app
near Locates a position near the specified target
ll -he latitude and longitude .comma-separated/ for the
center point of the map"
7 - '
2013 Intel Corporation.
Fast Track to Intel XDK New
(rgument Description
sll -he latitude and longitude .comma-separated/ from where
a business search should be performed"
spn -he appro*imate latitude and longitude span
t -he type of map to display
P Qoom level
saddr -he source address from which to generate driving
directions
daddr -he destination address from which to generate driving
directions"
-he following snippet illustrates how to generate a lin! that, when pressed,
would launch an i8( device's maps app with turn-by-turn directions:
var from1ddr = escape("7RBB 7=
t
%t '5 8BB9=");
var to1ddr = escape("8BBB 4 %t '5 8BB9=");
var tpl=KFa ref="maps*<<Mdaddr={B}Osaddr={7}"GClic/ #eF<aGK
location.ref = tpl.format(from1ddr,to1ddr);
Activating the .avigation App "or Android 'eb Apps
8pening the navigation app on Android can be a little tric!y since the
Android webview, which is used to drive native-apps functions slightly
differently than the native Android browser when it's running in standalone
mode"
,f running your code as a web app, the browser will respond similarly to
the techni0ue previously described for i8( devices L you simply need to
specify the url for maps"google"com as illustrated below:
var from1ddr = escape("7RBB 7=
t
%t '5 8BB9=");
var to1ddr = escape("8BBB 4 %t '5 8BB9=");
var tpl=KFa ref="ttp*<<maps.google.com<mapsM
daddr={B}Osaddr={7}"GClic/ #eF<aGK
location.ref = tpl.format(from1ddr,to1ddr);
2ou can also open the native 'oogle Oaps app by using the geo: uri" As
illustrated by the following use case, you can pass a latitude and longitude
as a comma-delimited list" -he P argument indicates Poom level on a scale
of 6-;< where 6 is the whole earth and ;< is is the highest Poom level"
Fa ref="geo*<<M
saddr=8B.;RR,9R.9ROdaddr=8B.A==,R;.9R;"G'avigateHF<aG
7 - 10
2013 Intel Corporation.
Usin De!ice Feat"res
&nfortunately, the Android +ebCiew that is used to run your app in
NnativeF mode does not recogniPe that a maps"google"com url or the geo:
uri should be opened in an e*ternal app"
Launching Googe +aps in the Cordova !nApp/ro0ser
An alternative to launching the native 'oogle
Oaps app on the device is to launch the
maps"google"com web app inside of a
ordova ,nAppRrowser"
-he ,nAppRrowser is a web browser that
displays when you invo!e the window"open./
method as illustrated below:
var from1ddr =
escape("7RBB 7=t %t '5 8BB9=");
var to1ddr =
escape("8BBB 4 %t '5 8BB9=");
var tpl="ttp*<<maps.google.com<mapsM
daddr={B}Osaddr={7}";
var loc =
tpl.format(from1ddr,to1ddr);
var ref = window.open(loc, K(.lan/K, Klocation=6esK);
Activating the .avigation App "or .ative Android Apps
Another alternative is to use a ordova plugin that enables you to launch
and Android intent" An intent is an abstract description of an operation to
be performed which can include launching an activity. ,n native Android
parlance, an activity is an app"
Detecting .ative vs 'eb
if (document.+"L.indeE&f( Kttp*<<K ) === ?7 OO
document.+"L.indeE&f( Kttps*<<K ) === ?7) {
<< Pone-ap application
} else {
<< 5e. page
}
7 - 11
2013 Intel Corporation.
Figure ): T*e Cor!o+a
,n(pp-ro.ser
Fast Track to Intel XDK New
'a(through 7)1: !nvo(ing &2terna Apps
,n this wal!through you will enhance the
contactdetail view by adding buttons that
enable the user to telephone, email, or get turn-
by-turn directions to their friend with beer"
Add buttons to a &,
reate a function to programmatically
clic! a dynamic lin!
&se special urls to invo!e e*ternal apps
%teps
Open the $roject
6" 8pen ,ntel 9#: %ew
;" lic! on the word PROJECTS in the top-
left corner of the '&,"
<" lic! the Open a Project button"
=" (elect the following file:
<ft$ntelDd/'ew<wal/<wal/>(8<wal/>(8.Ed/
Add buttons to the U!
>" 8pen contact!etai$"*tm$ in #esign mode"
?" 5rom the Contro$s @ Form panel, drag a -/TTO0 widget and drop it
on the top row, right-column of the page body in the canvas"
A" onfigure the following Rutton properties:
Oini: chec!ed
,con: ui-icon-phone
,con Position: ,con only
,d: btnPhone
B" 5rom the ontrols @ 5orm panel, drag a R&--8% widget and drop it
onto the design canvas, directly underneath the btnPhone button"
D" onfigure the following Rutton properties:
Oini: chec!ed
,con: ui-icon-mail
,con Position: ,con 8nly
,d: btnOail
6G" 5rom the ontrols @ 5orm panel, drag a R&--8% widget and drop it
onto the design canvas, directly underneath the btnOail button"
7 - 12
2013 Intel Corporation.
Figure 1: (!! 2uttons to
!ia$3 emai$3 an! na+igate
Usin De!ice Feat"res
66" onfigure the following Rutton properties:
Oini: chec!ed
,con: ui-icon-navigation
,con Position: ,con 8nly
,d: btn%av
6;" (ave the file
Create an &vent Listener "or the Teephone /utton
6<" ,nside the ontact#etail object, define a method named
configureRuttons./"
6=" ,n the ontact#etail"init./ method, invo!e the
ontact#etail"configureRuttons./ function directly underneath the
output#etails./ invocation"
!e"output,etails%'+
me.configure3uttons();
!e"output,istance%'+
6>" ,nside the onfigureRuttons./ method, bind a tap event listener to the
btnPhone button so that it launches the user's phone application and
dials their friend's phone number when tapped"
6?" Cerify that your code appears similar to the following:
I("J.tnPone")..ind("tap", function(e) {
var p = Contact)etail.contact)ata.pone;
if (p H= "") {
var telLin/ = "tel*" C p;
location.ref=telLin/;
} else {
alert("Pone 'um.er 'ot 1vaila.le");
}
});
6A" (ave the file"
6B" lic! on the Test tab"
6D" lic! the Pus* Fi$es button
;G" Launch ,ntel App Preview on your device, scan the 7R code, and test
your app"
Create an &vent Listener "or the &#ai /utton
;6" Return to inde*"html in ode mode"
;;" &nderneath the code that you added in step 6=, bind a tap event listener
to the btnOail button so that it launches the user's email application
and sets default subject and body te*t when tapped"
7 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
;<" Cerify that your code appears similar to the following:
I("J.tn#ail")..ind("tap", function(e) {
var mailLin/ = "mailto*{B}Msu.Nect={7}O.od6={8}";
mailLin/ = mailLin/.format(
Contact)etail.contact)ata.email,
escape("Can $ come over nowM"),
escape("'eed to cat a.out someting .igH")
);
location.ref = mailLin/;
});
;=" Launch ,ntel App Preview on your device, scan the 7R code, and test
your app"
Create an &vent Listener "or the .av /utton
;>" After the code that you inserted from step ;;, bind a tap event listener
to the Kbtn%av button" 2our code should appear similar to the
following:
I("J.tn'av")..ind("tap", function(e) {
});
;?" ,nside the event handler function, insert an if-elseif-else bloc! that
determines whether the user is using an Android device or an i8(
device" ,f the device is not i8( or Android, output an alert message"
2our code should appear similar to the following:
-%".btn/av"'"bind%"tap"* &unction%e' (
if (<1ndroid<i.test(navigator.user1gent)) {
} else if (<iPoneQiPadQiPod<i.test(navigator.user1gent)) {
} else {
alert(K)evice not supportedK);
return;
}
)'+
;A" ,nside the if./ bloc! for Android, define a local variable named
maps&rl and set it e0ual to the google maps url with '$- parameters
named daddr and saddr that point to lat1lng placeholders"
i& %/0ndroid/i"test%navigator"user0gent'' (
var maps+rl = "ttp*<<maps.google.com<mapsMdaddr={B},
{7}Osaddr={8},{9}";
)
7 - 1#
2013 Intel Corporation.
Usin De!ice Feat"res
;B" After the code that you inserted in the prior step, replace the
placeholders with the lat1lng coordinates of the contact#ata and
currentPosition properties of the ontact#etail object"
maps+rl = maps+rl.format(
Contact)etail.contact)ata.lat,
Contact)etail.contact)ata.lng,
Contact)etail.currentPosition.lat(),
Contact)etail.currentPosition.lng()
);
;D" After the code that you inserted from the prior step, launch the url in an
inAppRrowser"
window.open(maps+rl, K(.lan/K, Klocation=6esK);
<G" ,nside the if./ bloc! for i8(, define a local variable named maps&rl
and set it e0ual to the Apple maps url with '$- parameters named
daddr and saddr that point to lat1lng placeholders"
i& %/0ndroid/i"test%navigator"user0gent'' (
var !aps1rl = "ttp2//!aps"google"co!/!aps"+
) else i& %/i$one3i$ad3i$od/i"test%navigator"user0gent''(
var maps+rl = "maps*<<Mdaddr={B},{7}Osaddr={8},{9}";
) else (
/4 o!itted &or brevity 4/
)
<6" After the code that you inserted in the prior step, replace the
placeholders with the lat1lng coordinates of the contact#ata and
currentPosition properties of the ontact#etail object"
maps+rl = maps+rl.format(
Contact)etail.contact)ata.lat,
Contact)etail.contact)ata.lng,
Contact)etail.currentPosition.lat(),
Contact)etail.currentPosition.lng()
);
<;" After the code that you inserted in the prior step, launch the url by
setting the location"href property as illustrated below:
location.ref = maps+rl;
<<" (ave the file"
<=" lic! on the Test tab"
<>" lic! on Pus* Fi$es"
<?" Launch ,ntel App Preview on your device and test the app"
L $nd of +al!through --
7 - 1$
2013 Intel Corporation.
Fast Track to Intel XDK New
Listening to the Acceero#eter
2ou can access a device's accelerometer through either 4ava(cript's
#eviceOotion AP, or, alternatively, via ordova's Accelerometer support"
-he #eviceOotion AP, enables you to listen for changes in the device's
orientation as well as changes in movement"
Rrowsers that currently support the #eviceOotion AP, include:
i8( (afari =";"6 .and above/
Android ="G"< .default browser/
8pera Oobile .Android/
Rlac!Rerry PlayRoo! ;"G
5irefo* for Android
5irefo*8( #evices
Detecting Changes to Device Orientation
Refore using the #evice8rientation AP,, verify that the
#evice8rientation$vent is supported by your browser as illustrated in the
following snippet:
if (window.)evice&rientation!vent) {
<< insert coolness ere
} else {
alert("1w, %napH CanKt determine device orientation");
}
2ou can subse0uently add an event listener that is triggered whenever the
user's device changes orientation along different a*es" ,n the following
e*ample, the event handler simply outputs the orientation of the device to
the debugging console"
window.add!ventListener(KdeviceorientationK, function(e) {
var out = "alpa* {B}, .eta* {7}, gamma* {8}";
console.log(out.format(
e.alpa,
e..eta,
e.gamma
));
});
%ote the following:
a$p*a is the direction that the device is facing"
2eta is the angle that the device is tilted from front-to-bac!"
gamma is the angle that the device is tilted left-to-right"
7 - 1%
2013 Intel Corporation.
Usin De!ice Feat"res
Detecting Changes in Device +otion
Listen to the #eviceOotion$vent to poll for the rotation and acceleration
of the device"
(ince support for this AP, varies, you should always verify that the event is
available by including the following code snippet:
if (window.)evice#otion!vent) {
<< .ring te awesome ere
} else {
alert("1w, %napH 'o sa/e gesture for 6ouH");
}
Attach your event handler to the devicemotion event as illustrated below:
window.add!ventListener(KdevicemotionK, function(e) {
<< get refres interval*
<< e.interval
<< acceleration info*
<< e.acceleration.E
<< e.acceleration.6
<< e.acceleration.S
<< acceleration info including gravit6*
<< e.acceleration$ncluding-ravit6.E
<< e.acceleration$ncluding-ravit6.6
<< e.acceleration$ncluding-ravit6.S
<< rotation rate
<< e.rotation"ate.alpa
<< e.rotation"ate..eta
<< e.rotation"ate.gamma
}, false);
Using the %ha(e3js Librar,
-he (ha!e"js library, developed by Ale* 'ibson .http:11al*gbsn"co"u!1/ and
available under an O,- license, gives you a high-level event that's fired
when the user Nsha!esF their device" 2ou can set up the event listener by
simply loading his sha!e"js script and then listen for a Nsha!eF event as
illustrated by the following snippet:
window.add!ventListener(Ksa/eK, sa/e!vent)id&ccur, false);
7 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
'a(through 7)4: Listening "or a 5%ha(e6
,n this wal!through you will use the sha!e"js library to capture a sha!e
gesture and display information about a randomly selected friend"
Load the sha!e"js library
Review the devicemotion api
onfigure an event listener
%teps
Open the $roject
6" 8pen ,ntel 9#: %ew
;" lic! on the word PROJECTS in the top-left corner of the '&,"
<" lic! the Open a Project button"
=" (elect the following file:
<ft$ntelDd/'ew<wal/<wal/>(9<wal/>(9.Ed/
>" 8pen inde*"html in ode Ciew"
?" Review the getRan!omFrien!%& and *an!$e(ppS*a4e%& methods of
the App object"
Listen "or a %ha(e Gesture
A" +here indicated by the comment, insert a Jscript@ tag to load the
js1sha!e1sha!e"js file"
B" 8pen the js1sha!e1sha!e"js file and review its contents" %ote that it uses
the #eviceOotion AP,"
D" Return to inde*"html in ode mode"
6G" ,nside the App"init./ method, where indicated by the comment, listen
for a Nsha!eF event" +hen triggered, invo!e the App"handlesha!e./
method"
window.add!ventListener(
Ksa/eK,
1pp.andle1pp%a/e,
false
);
66" (ave the file"
7 - 1&
2013 Intel Corporation.
Usin De!ice Feat"res
Test 7our 'or(
6;" -est the app using ,ntel App Preview"
Note: this feature cannot be tested on the emulator at the current time
6<" Run the app and sha!e your phone .be careful not to drop itS/" %ote
that sha!ing the phone selects a random friend and displays his1her
detail information"
L $nd of +al!through --
7 - 1'
2013 Intel Corporation.
Fast Track to Intel XDK New
Listening "or $ush .oti"ications
Push notifications transfer messages through a constantly open ,P
connection to mobile devices" %otifications may include badges, sounds or
custom te*t alerts" -hey can play a vital role in increasing user
engagement"
$ach mobile operating system vendor has a gateway from which
notifications are transmitted" 2ou can build your own front-end to these
gateways or use a <
rd
party push notification vendor" -ypically these
vendors offer '&, and web-service based AP,'s that enable you to target
specific groups of users based on metadata collected by your apps, their
current geographic position, username, and more"
Cendors include, but are not limited to:
AppOobi loud (ervices .PushOobi/
&rban Airship
Push+oosh
Oi*panel
-his course details how to receive push notifications from the PushOobi
service to Android devices"
7 - 20
2013 Intel Corporation.
Figure 5: Sen!ing messages to !e+ices from Pus*6o2i
Usin De!ice Feat"res
Registering ,our App to Receive .oti"ications
-he first step to enabling push notifications is to enable push notification
support for each mobile platform via the R&,L# tab in the ,ntel 9#:"
lic!ing on the P&(3 tab, as illustrated by 5igure A, presents you with an
8(-specific form" Refore you can proceed, you'll need to register your app
with the 'oogle loud Oessaging (ervice"
7 - 21
2013 Intel Corporation.
Figure 7: Configuring Pus* notification ser+ices for (n!roi!
Fast Track to Intel XDK New
Registering 0ith the Googe Coud +essaging %ervice
,n order to enable 'O for your app, you'll need to register your project in
the 'oogle loud onsole at http:11cloud"google"com"
After registering your project, you'll need to clic! on the AP,s M Auth tab
and enable 'oogle loud Oessaging for Android as illustrated in 5igure B"
Registering the $ush+obi App as the Cient
Rather counter-intuitively, what you need to register in the ne*t step of the
process is not your android app, but actually a web application L since it's
actually the PushOobi service that will be communicating with the 'O
to send messages L and PushOobi is a web-based application"
7 - 22
2013 Intel Corporation.
Figure 8: Ena2$ing Goog$e C$ou! 6essaging
Figure 9: Registering t*e Pus*6o2i front:en! for Frien!s .it* -eer
Usin De!ice Feat"res
Getting the .ecessar, Credentias
,n order to configure PushOobi to be able to communicate properly with
'O, you'll need to retrieve two identifiers from the 'oogle loud
onsole:
-he +eb Application's Rrowser :ey
-he Project's ,dentifier
2ou can retrieve the first item by opening the Rrowser :ey section of your
AP,s +eb Application detail page as illustrated by 5igure 6G"
8nce you've copied the browser !ey to your clipboard, you must paste it
into the Api :ey .>d/ field in the ,ntel 9#: Ruild @ Push screen as
illustrated in figure A"
7 - 23
2013 Intel Corporation.
Figure 1;: Getting t*e -ro.ser <ey
Fast Track to Intel XDK New
-he second piece of information L the project's identifier, you can get by
clic!ing on your project's O+er+ie. tab as illustrated by figure 66" 2ou'll
need to copy the Project Number and paste it into the Project ,d .>/ field
as illustrated in 5igure A"
Using the inte32d(3noti"ication A$!
After you've configured the PushOobi service to communicate with the
'oogle loud Oessenger gateway, you can add code to your app to listen
for push notifications and handle them when the occur"
-he PushOobi client-side AP, registers a user .or device/ with the push
service and listens for incoming messages" -he code is largely boilerplate
and can be easily copied into an app"
$ssentially, the process is bro!en into three steps:
6" hec! to see if the user1device is registered with the service
;" Register the user1device if necessary
<" Listen for notifications and handle them when they occur"
Chec(ing Device and User Registration
,nvo!e the intel"5d6"noti&ication"cec6$us1ser%' method to
determine if a user account has been registered with the PushOobi service"
-he general synta* is:
intel.Ed/.notification.cec/Pus+ser(
username,
password
);
%ote that if your app does not re0uire authentication, you can simply
substitute the device's uni0ue identifer .&&,#/ for both the username and
password as illustrated below:
intel.Ed/.notification.cec/Pus+ser(
intel.Ed/.device.uuid,
intel.Ed/.device.uuid
);
7 - 2#
2013 Intel Corporation.
Figure 11: Getting t*e Project=s ,D
Usin De!ice Feat"res
+hen the chec!Push&ser./ method has completed, it will fire an event
named intel"5d6"noti&ication"pus"enable and pass in an event
object where you can inspect the result and register the user, if necessary:
var notifications = {
did1dd * false,
register* function(event) {
if(event.success === false) {
if (notifications.did1dd === false) {
notifications.did1dd = true;
intel.Ed/.notification.alert(
")oing addPus+ser now...",
"#6 #essage",
"&4"
);
<<0r6 adding te user now ? sending uni,ue user id,
<<password, and email address.
intel.Ed/.notification.addPus+ser(
intel.Ed/.device.uuid,
intel.Ed/.device.uuid,
KnoLemail.comK
);
<<0is will fire te pus.ena.le event again,
<<so tat is w6 we use did1dd to ma/e sure
<<we dont add te user twice if tis fails for an6 reason.
return;
}
intel.Ed/.notification.alert(
"'otifications Tailed* " C event.message,
"#6 #essage",
"&4"
);
return;
}
var msg = event.message QQ KsuccessK;
intel.Ed/.notification.alert(
"'otifications !na.led* " C msg,
"#6 #essage",
"&4"
);
}
<< register event listener
document.add!ventListener(
"intel.Ed/.notification.pus.ena.le",
notifications.register,
false
);
7 - 2$
2013 Intel Corporation.
Fast Track to Intel XDK New
Listening "or .oti"ications
After the user's account has been registered, the receiving of push
notifications will trigger the
intel"5d6"noti&ication"pus"receive event" 2ou can code this
handler any way that you wish, although typically you'll use the following
methods to read, parse, and delete messages:
inte$"'!4"notification"get0otificationList%&
Returns an array of strings that correspond to the identifiers for
received messages"
inte$"'!4"notification"get0otificationData%notification id&
Returns an object containing the properties of the specified notification
8bject property names include: !sg and data"
inte$"'!4"notification"!e$etePus*0otifications%notification i!&
#eletes the specified notification
A typical notification handler resembles the following snippet:
var notifications = {
receivedPus* function() {
var ' = intel.Ed/.notification;
var m6'otifications='.get'otificationList();
<< $t ma6 contain more tan one message, so loopH
var len=m6'otifications.lengt;
if(len G B) {
for(i=B; i F len; iCC) {
<<-et message id
msg&.N='.get'otification)ata(m6'otificationsUiV);
if(t6peof msg&.N == "o.Nect" OO
msg&.N.id == m6'otificationsUiV){
<< )ispla6 te message now.
<< Wou can do tis owever 6ou li/e ?
<< it doesnKt ave to .e an alert.
'.alert(msg&.N.msg C "Xn" C msg&.N.data C "Xn" C
msg&.N.user/e6, "pus#o.i #essage","&4");
<< 1lwa6s mar/ te messages as read and delete tem.
<< $f 6ou dont, 6our users will see tem repeated
'.deletePus'otifications(msg&.N.id);
return;
}
} << for
} << if()
} << function
} << class
<< listen for event
document.add!ventListener(
"intel.Ed/.notification.pus.receive",
notifications.receivedPus,
false);
7 - 2%
2013 Intel Corporation.
Usin De!ice Feat"res
Testing in the &#uator
2ou can verify your event handlers and view the result of your push
notification handling by running your app in the $mulator as depicted in
5igure 6;" -yping a message into the P&(3O8R, ($RC,$ panel
simulates the firing of an intel"5d6"noti&ication"pus"receive
event"
7 - 27
2013 Intel Corporation.
Figure 1: Sen!ing a test message in t*e emu$ator"
Fast Track to Intel XDK New
Testing on a Device
-est your app on a physical device by going through the application build
process, install the app on your device, and then access the PushOobi
service under the 9#: (ervices tab as illustrated in figure 6<"
#evices that have properly registered themselves with the PushOobi
service should appear under the &ser Oanagement tab" %ote that the
PushOobi console allows you to target individual users by name, device
platform, or custom filter"
7 - 2&
2013 Intel Corporation.
Figure 1#: Sen!ing a message +ia Pus*6o2i
Usin De!ice Feat"res
'a(through 7)8: 9anding $ush .oti"ications
#uring this wal!through you will configure
PushOobi to send messages through the 'oogle
loud Oessaging (ervice" 2ou will then add code
to your application to register the device and
handle push notifications" 2ou'll test your wor! in
the $mulator and on a physical device"
Register a Push %otification App with 'oogle
onfigure PushOobi to communicate with
'O
Listen for push messages to your app
%teps
Open the $roject
6" 8pen ,ntel 9#: %ew
;" lic! on the word PROJECTS in the top-left corner of the '&,"
<" lic! the Open a Project button"
=" (elect the following file:
<ft$ntelDd/'ew<wal/<wal/>(R<wal/>(R.Ed/
Con"igure the %erver $ush %ervice
>" lic! on the -ui$! -ab
?" lic! on -ui$! @ (n!roi!
A" lic! /p$oa! Co!e
B" lic! on the Pus* tab
D" lic! on the radio button labeled NConfigure t*is app for pus*
messagingF
6G" lic! O<"
Con"igure Googe Coud +essaging :GC+;
66" 8pen a web browser to the following &RL:
ttp*<<cloud.google.com<console
6;" lic! the Create Project button"
6<" $nter the following information:
Project %ame: 5riends with Reer
7 - 2'
2013 Intel Corporation.
Figure 1): >an!$ing
Pus* 0otifications
Fast Track to Intel XDK New
6=" lic! the Create button"
$roceed through the %+% veri"ication process
6>" lic! on (P,=s ? (ut*
6?" -urn the Goog$e C$ou! 6essaging for (n!roi! to 8%"
6A" lic! on Registere! apps
6B" lic! on the Register App button and enter the following information:
%ame: 5riends with Reer
Platform: +eb Application
6D" lic! the Register button"
;G" lic! on -ro.ser <ey
;6" opy the AP, :ey to your clipboard
;;" Paste the AP, :ey into the ,ntel 9#: AP, :ey field .>d/
;<" lic! on Projects
;=" lic! on Frien!s .it* -eer
;>" opy the Project 0um2er to your clipboard
;?" Paste the project number into the ,ntel 9#: Project ,D field"
;A" lic! Go to 0e't Step"
Listen "or $ush .oti"ication &vents
;B" lic! on the De+e$op tab"
;D" 8pen in!e'"*tm$ in ode mode"
<G" arefully review the 0otifications object, its properties, and its
methods that start on line AGD"
<6" +here indicated by the comment in the onDe+iceRea!y%& handler, add
an event listener for the inte$"'!4"notification"pus*"ena2$e event that
invo!es the notifications"register event"
var on,evice7eady=&unction%'(
//ide splas screen
intel"5d6"device"ide8plas8creen%'+
document.add!ventListener(
"intel.Ed/.notification.pus.ena.le",
notifications.register,
false
);
)+
7 - 30
2013 Intel Corporation.
Usin De!ice Feat"res
<;" ,mmediately after the code that you inserted in the prior step, add an
event listener that invo!es the notifications"recei+e!pus* method
when an inte$"'!4"notification"pus*"recei+e event is fired"
var on,evice7eady=&unction%'(
//ide splas screen
intel"5d6"device"ide8plas8creen%'+
docu!ent"add9vent:istener%
"intel"5d6"noti&ication"pus"enable"*
noti&ications"register*
&alse
'+
document.add!ventListener(
"intel.Ed/.notification.pus.receive",
notifications.receivedPus,
false
);
)+
<<" ,mmediately after the code that you inserted in the prior step, chec! to
see if the device is registered with the PushOobi service" 2our code
should appear as follows:
var on,evice7eady=&unction%'(
//ide splas screen
intel"5d6"device"ide8plas8creen%'+
docu!ent"add9vent:istener%
"intel"5d6"noti&ication"pus"enable"*
noti&ications"register*
&alse
'+
docu!ent"add9vent:istener%
"intel"5d6"noti&ication"pus"receive"*
noti&ications"received$us*
&alse
'+
intel.Ed/.notification.cec/Pus+ser(
intel.Ed/.device.uuid,
intel.Ed/.device.uuid
);
)+
<=" (ave the file"
Test the %ervice in the &#uator
<>" lic! on the Emu$ate -ab
<?" (end a test message from the P&(3O8R, ($RC,$ panel"
L $nd of +al!through --
7 - 31
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit %u##ar,
2ou can retrieve a device's current position by using either the ordova
AP, or the build-in navigator"geolocation"geturrentPosition./ method"
2ou can activate the phone dialer and email client by calling special
&R,'s"
(upport for launching the built-in navigation app varies between
platforms and delivery systems
&se the accelerometer to handle changes in orientation to the device"
-he devicemotion api enables you to detect changes in how the device
is being handled L including Nsha!eF gestures"
,mplement push notifications to enhance user engagement"
2ou can create your own push notification messaging front-end or
choose from a variety of third-party services"
,ntel 9#: %ew directly supports the PushOobi front-end for sending
push notifications"
2ou will need to configure PushOobi for each of the platforms that
you intend to support .i8(, Android, +indows Oobile/
7 - 32
2013 Intel Corporation.
Usin De!ice Feat"res
Unit Revie0
6" 2ou must use the ordova AP, to access the device's accelerometer
.true1false/T
;" #escribe the process for activating the device's phone dialer and
default email application"
<" +hich method do you call to get the device's current positionT
=" +hy should you always include an error callbac! function when
attempting to get the device's current positionT
>" ,ntel 9#: apps can only receive push notifications from the PushOobi
service .true1false/
7 - 33
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 8:
Integrating Multimedia
Unit Objectives
After completing this unit, you should be able to:
Add audio to your applications
Integrate video from different sources into your app
Use JavaScript to implement custom player controls for your media
Unit Topics
Playing Audio and Video
8 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Playing Audio and Video
Intel X! "e# has design$time #idgets for deploying native %&'()
audio and video players* It also has #idgets for embedding +ou&ube videos
and Vimeo presentations #ithin your app*
&he goal of the %&'( ) audio,video specification #as to natively support
data formats that are royalty$free, have good data compression #hile not be
cpu$intensive to decode, and a hard#are decoder* It states that bro#sers
should support &heora video and Vorbis audio, as #ell as the -gg container
for a placeholder, since these codecs are not affected by any .no#n patents*
Syntactically, the playbac. of audio and video is handled through the
/video0 , /audio0, and /source0 commands*
Adding HTM! Video
+ou can insert bro#ser$based video into your #eb page using the /video0
tag* &he follo#ing attributes are supported:
Attribute Description
autoplay
1oolean attribute, causes the user agent to start playing
the media as soon as it is able*
controls
1oolean attribute indicating #hether the author has not
provided a custom controller using Javascript and #ould
li.e to use the native set of controls*
height
&he height of the control, in pi2els
width
&he #idth of the control, in pi2els
loop
1oolean attribute indicating #hether the media should
continue playing from the start of the file once it has
reached its end*
preload
3none3 indicates to the bro#ser that that the author
#ill probably not need the media resource*
3metadata3 hints to the bro#ser that the author #ill
probably not need the media resource but that pre$
fetching the resource metadata 4dimensions, first
frame, duration5 is #orth#hile*
3auto3 hints to the bro#ser that the author e2pects the
video to be played and therefore it should
optimistically cache the resource*
poster
6ives the address of an image file that the user agent can
sho# #hile no video data is available* &he attribute, if
present, must contain a valid non$empty U7( potentially
surrounded by spaces* &he image is supposed to be a
representative frame from the video*
8 - 2
2013 Intel Corporation.
Integrating !lti"e#ia
Attribute Description
src
&he U7( of the media asset* 'ay be overridden by the
use of the /source0 element*
&he follo#ing e2ample illustrates a simple invocation of the /video0 tag:
<video
width="320"
height="240"
controls="true"
src="video1.ogg"
preload="auto"
poster="titleframe.jpg">
et a real !rowser" #o.
<$video>
"evie#ing supported $ile $ormats
Support for video formats varies, #ith most vendors supporting either the
8eb' or 'P9 formats* Ironically, support for -gg as stipulated in the
%&'() specification, is only included in the mobile -pera and :irefo2
bro#sers*
Browser WebM MP4
Android +es Partial
iOS "o +es
Blackberry "o +es
IE Mobile "o +es
Opera Mobile "o +es
Chroe Android +es +es
!ire"o# Android +es Partial
In order to support all mobile bro#sers, you;ll therefore need to support
both 8eb' and 'P9 formats by using the /source0 element as illustrated
belo#:
<video width="320"
height="240"
controls="true">
<source src="video1.we!m" t#pe="video$we!m" $>
<source src="video1.mp4" t#pe="video$mp4" $>
<$video>
8 - 3
2013 Intel Corporation.
Fast Track to Intel XDK New
Inserting Video #it% Intel &'( )e#
As illustrated in :igure <, Intel
X! "e# has a Video #idget
that enables you to drag and drop
a video into your app*
Supported config properties
include:
8ebm Source :ile
'p9 Source :ile
Autoplay
=ontrols
(oop
Preload
Video =aption
*uilding your o#n controls
&he %&'() media element supports the follo#ing properties and methods
from #hich you could build a custom playbac. controls:
$ead Only
Property
Description
paused 7eturns true if the playbac. is paused
ended 7eturns true if playbac. has ended
readyState escribes #hether the video is ready to be
played and,or enough of the video has been
preloaded for it to play #ithout intermediate
pauses*
played 7eturns a &ime7anges ob>ect representing the
range of the media that has been played
see.ing 7eturns true if the user agent is currently see.ing
duration 7eturns the length of the media resource, in
seconds
start&ime 7eturns the earliest possible position, in seconds*
"ote that this might not be ?ero$based if the
resource is being streamed in real$time*
see.able 7eturns a &ime7anges ob>ect that represents the
ranges of the media resource to #hich it is
possible for the user agent to see.*
8 - $
2013 Intel Corporation.
!i%ure &' Intel (D) *ew +ideo Wid%et
Settin%s
Integrating !lti"e#ia
$ead,Write
Property
Description
playbac.7ate 7eturns the current playbac. rate
defaultPlaybac.7ate 7eturns the default playbac. rate, #here <*@ is
normal speed*
volume 7etuns the current playbac. volume, in a range
of @*@ to <*@ #here @*@ is the Auietest and <*@ is
the loudest*
current&ime 7eturns the current playbac. position, in
seconds* =an be set to see. to a specific time*
muted 7eturns true if the audio is muted, false if not*
Method Description
load45 =auses the element to reset and start selecting
and loading a ne# media resource from scratch*
pause45 Sets the paused attribute to true, loads the media
resource if necessary*
play45 Sets the paused attribute to false, loads the media
resource, and starts playbac.*
canPlay&ype4type5 7eturns the empty string 4a negative response5,
3maybe3, or 3probably3 if the user agent
determines that it can play media resources of
the given type*
&he follo#ing 'edia events are also available:
ondurationchange
onemptied
onerror
onloadedmetadata
onloadstart
onpause
onplay
onplaying
onsee.ed
onsee.ing
onstalled
onsuspend
ontimeupdate
onvolumechange
on#aiting
8 - %
2013 Intel Corporation.
Fast Track to Intel XDK New
Using these properties and methods, you could create your o#n
playbac.,pause button as illustrated by the follo#ing snippet:
<head>
<script language="javascript">
ena!le!uttons = function%& '
document.get(lement)#*d%+pla#!utton+&.disa!led =
false,
-
pla#pause = function%& '
var o!j.edia = document.get(lement)#*d%+m#media+&,
var o!j)utton = document.get(lement)#*d%+pla#!utton+&,
if %o!j.edia.paused& '
o!j.edia.pla#%&,
o!j)utton.value="/ause",
- else '
o!j.edia.pause%&,
o!j)utton.value="/la#",
-
-
<$script>
<$head>
<!od#>
<video
width="320"
height="240"
controls="false"
on0an/la#1hrough="ena!le)uttons%&"
id="m#media">
<source src="video1.we!m" t#pe="video$we!m" $>
<source src="video1.mp4" t#pe="video$mp4" $>
<$video>
<input t#pe="!utton"
value="/la#"
on0lic2="pla#pause%&"
id="pla#!utton">
...
<$!od#>
8 - &
2013 Intel Corporation.
Integrating !lti"e#ia
Playing Videos $rom +ouTube
+ou can play +ou&ube videos from your app by inserting a video;s embed
code into your app* &he embed code uses an /iframe0 and, as illustrated in
:igure B, the url is located #ithin the Share$Cmbed bloc. underneath each
video*
8 - '
2013 Intel Corporation.
!i%ure -' $etrie.in% a /ou0ube .ideo ebed url
Fast Track to Intel XDK New
Intel X! "e# includes a design$time video #idget that #ill insert the
/iframe0 code for you D you simply need to enter the embed U7( into the
+ou&ube Settings panel as illustrated in figure E*
,mbedding -ontent $rom Vimeo
Vimeo is a video$sharing #ebsite similar in nature to +ou&ube* Unli.e
+ou&ube, ho#ever, it does not play advertisements before, during, or after
your videos* Vimeo has a significant follo#ing among the creative and
business communities and is directly supported by Intel X! "e#*
+ou can embed Vimeo videos into your app by using the same /iframe0
techniAue that had been previously described for embedding +ou&ube
videos* As illustrated in :igure 9, you can copy the U7( to your clipboard
by clic.ing on a video;s Share button and then paste it into the X! "e#
Vimeo #idget Settings panel*
8 - 8
2013 Intel Corporation.
!i%ure 1' Con"i%urin% a /ou0ube .ideo
!i%ure 4' 2ettin% an ebed 3$4 "ro +ieo
Integrating !lti"e#ia
.or/ing #it% Audio
&he /audio0 tag functions similarly to the /video0 tag in that it enables
you to play a media file #ithout reAuiring the use of a bro#ser plug$in and
is typically used in mobile apps to play songs and podcasts*
Audio support in mobile bro#sers remains problematic for use in games*
&iming issues, lags, lac. of pre$loading, inability to play multiple clips
simultaneously, and general bugginess ma.e it unsuitable for playing short
sound$effect clips #ith precision timing* In the near future, the recently
introduced %&'() Audio API may provide some relief for html) mobile
game developers*
Supported attributes of the /audio0 element include the follo#ing:
Attribute Description
autoplay 1oolean attribute, causes the user agent to start playing
the media as soon as it is able*
controls 1oolean attribute indicating #hether the author has not
provided a custom controller using Javascript and #ould
li.e to use the native set of controls*
"ote that Android devices do not have native audio
controls*
loop 1oolean attribute indicating #hether the media should
continue playing from the start of the file once it has
reached its end*
preload 3none3 indicates to the bro#ser that that the author
#ill probably not need the media resource*
3metadata3 hints to the bro#ser that the author #ill
probably not need the media resource but that pre$
fetching the resource metadata 4dimensions, first
frame, duration5 is #orth#hile*
3auto3 hints to the bro#ser that the author e2pects the
video to be played and therefore it should
optimistically cache the resource*
"ote: preload is not supported on most mobile bro#sers*
src &he U7( of the media asset* Use the /source0 element
to specify alternative file formats for broader user agent
compatibility*
As illustrated belo#, you should include both mpE and -gg Vorbis files in
order to support the broadest range of devices*
<audio
controls="false"
on0an/la#1hrough="ena!le)uttons%&"
id="m#media">
<source src="audiofile.mp3" t#pe="audio$mpeg" $>
<source src="audiofile.ogg" t#pe="audio$ogg" $>
<$audio>
8 - (
2013 Intel Corporation.
Fast Track to Intel XDK New
Using 0audio1 Properties
&he /audio0 element e2poses a number of runtime properties that help you
determine the clip;s current state:
Property Description
current&ime "umber* &he playhead position, e2pressed as seconds
duration "umber* Playbac. time for the clip, in seconds*
muted 1oolean* 7eturns true if volume is muted
paused 1oolean* 7eturns true if media is paused*
volume :loat* Volume level, bet#een @ and <*
istening $or 0audio1 ,vents
+ou can listen on the follo#ing events #hich are thro#n by an Audio
ob>ect*
E.ent Description
canplay &he media can be played, but may need to pause #hile
do#nloading*
canplaythroug
h
Indicates that the media can be played through #ithout
pausing*
progress :ires to indicate progress at do#nloading the media file*
&ypically fires every B)@ ms but can be unreliable on
mobile devices* :or better granularity, call a method
using #indo#*setInterval45
ended &he end of the media #as reached and playbac. #as
stopped*
play &he media has started playing*
volumechange &he volume level has been ad>usted*
8 - 10
2013 Intel Corporation.
Integrating !lti"e#ia
2utures: Using t%e HTM! Audio API
As previously discussed, manipulation of audio in Javascript is Auite
limited* A ne# %&'() Audio API is under development, ho#ever, support
remains limited to the follo#ing bro#sers:
i-S Safari F*@G
=hrome E< for Android
:irefo2 B) for Android
'ost des.top bro#sers
4e2cluding 'icrosoft Internet
C2plorer5
:eatures of the %&'() Audio API include:
An Audio=onte2t class for
managing and playing all sounds*
Support for playing multiple
sound sources simultaneously*
(oading sounds via the
X'(%&&P7eAuest ob>ect #ith
audio decoding methods*
Scheduling precise sound
playbac. for games*
=ross$fading bet#een sounds
Applying filter effects*
&he follo#ing code snippet illustrates ho# you could use the %&'()
Audio API to load a sound file*
var music)uffer = null,
$$ 3i4 up prefi4ing
window.5udio0onte4t = window.5udio0onte4t 66
window.we!2it5udio0onte4t,
var conte4t = new 5udio0onte4t%&,
function load7ound%url& '
var re8uest = new 9.:;ttp<e8uest%&,
re8uest.open%+(1+" url" true&,
re8uest.response1#pe = +arra#!uffer+,
$$ =ecode as#nchronousl#
re8uest.onload = function%& '
conte4t.decode5udio=ata%
re8uest.response"
function%!uffer& '
music)uffer = !uffer,
-"
function %err& '
alert%"0ould not decode audio file"&,
-
&,
-
re8uest.send%&,
-
load7ound%+100)ottles>f)eer>nthe?all.mp3+&,
Note: See http://www.html5rocks.com/en/tutorials/webaudio/intro/ for a
detailed introduction to the html5 Web Audio API.
8 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
.al/t%roug% 834: Playing Videos
In this #al.through you #ill add streaming video playbac. from Vimeo to
your application as #ell as use the native html) /video0 element
Integrate video from Vimeo
Use the %&'() /video0 element to play an 'P9 file*
5teps
Open t%e Project
<* -pen Intel X! "e#
B* =lic. on the #ord P$O5EC0S in the top$left corner of the 6UI*
E* =lic. the Open a Pro6ect button*
9* Select the follo#ing file:
$ft*ntel9d2@ew$wal2$wal2AB1$wal2AB1.4d2
Integrate Video $rom Vimeo
)* -pen drin.*html in esign mode*
F* :rom the =ontrols 0 'edia panel, drag a Vimeo #idget and drop it
onto the center of the esign =anvas*
H* =onfigure the follo#ing Vimeo Settings:
Src: ,,player*vimeo*com,video,IF@JHBE
Autoplay: chec.ed
(oop: chec.ed
J* =lic. on the 0ES0 tab*
I* =lic. the Push !iles button
<@* &est your application on a device using Intel App Previe#* +ou should
be able to play the Vimeo video by tapping on the rin.K tab of the
app*
Integrate .ebM6MP7 Video
<<* 7eturn to the drin.*html file in Intel X! "e#;s esign mode*
<B* 7ight$clic.,=md$clic. on the Vimeo video and select elete*
<E* 7ight$clic.,=md$clic. on the =olumn ob>ect and select elete*
<9* :rom the =ontrols 0 'edia panel, drag a Video #idget and drop it onto
the center of the esign =anvas*
8 - 12
2013 Intel Corporation.
Integrating !lti"e#ia
<)* Cnter the follo#ing Video Settings:
8ebm Src: ,,2d.training*com,ft2d.ne#,friends*#ebm
'p9 Src: ,,2d.training*com,ft2d.ne#,friends*mp9
Autoplay: true
=ontrols: true
(oop: true
<F* Save the file*
<H* =lic. on the 0ES0 tab*
<J* =lic. the Push !iles button
<I* &est your application on a device using Intel App Previe#* +ou should
be able to play the Vimeo video by tapping on the rin.K tab of the
app*
D Cnd of 8al.through $$
8 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit 5ummary
+ou can play audio and video #ithout the user of a plug$in
&he %&'() /audio0 and /video0 elements have API methods that
you can use to design custom player controls*
+ou should support both 8eb' and 'P9 video formats to ensure the
highest degree of compatibility*
Intel X! "e# has design$time #idgets for %&'() video as #ell as
playing assets hosted on +ou&ube*com and Vimeo*com
&he /audio0 element is not #ell$suited for playing sound effects in
games*
&he %&'() Audio API contains a very robust set of methods for
handling audio, ho#ever, it is not currently supported by the native
Android bro#ser*
8 - 1$
2013 Intel Corporation.
Integrating !lti"e#ia
Unit "evie#
<* 8hat is the purpose of the /video0 element;s poster propertyL
B* 8hat video file formats are natively supported by i-S and AndroidL
E* +ou cannot programmatically determine #here the MplayheadN is at
#hile a video or audio clip is playing 4true,false5*
9* &he Android bro#ser #ill automatically output playbac. controls for
/audio0 instances 4true,false5*
8 - 1%
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 9:
Theming
Unit Objectives
After completing this unit, you should be able to:
Understand how to work with vendor prefixes
Add web fonts to your application
Enhance your app's typography
Apply background gradients and images
Use Themeoller to visually prototype a application widgets
Unit Topics
!orking with "##$ on %obile &evices
Enhancing 'onts and Typography
Enhancing (ackgrounds
!orking with Themeoller
9 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Working with CSS3 on Mobile Devices
)enerally speaking, most advanced features of "##$ are well*supported by
mobile browsers+ "##$ adds support for many important functions that are
critical for simulating native app behavior and minimi,ing the use of
-hacks. that were typically graphics intensive and led to slower download
times and increased memory re/uirements+ 0ey features include:
ounded borders
&ownloadable 'onts
Enhanced Typography
#hadowing
Transparency
(etter text overflow handling
(ackground si,ing and
positioning
"##*based 0eyframe Animation
Hn!ling "en!or #re$i%es
1endor prefixes in "## generally denote a "## property that is uni/ue to a
specific browser or may not have been officially ratified by the !$"+
Typical vendor prefixes that you'll encounter in mobile development
include:
Prefix Description
*webkit* !ebkit browsers 2typically i3# and Android4
*mo,* %obile 'irefox
*o* %obile 3pera
*ms* %obile 5E
As illustrated by the following snippet, these vendor prefixes can make
supporting "## files somewhat laborious as the same declaration must be
repeated multiple times in order to achieve full cross*platform
compatibility:
.box_gradient {
background-color: #c0c0c0; // fallback
background-image: linear-gradient(#ffffff,#c0c0c0);
background-image: -webkit-linear-gradient(#ffffff,#c0c0c0);
background-image: -mo-linear-gradient(#ffffff,#c0c0c0);
background-image: -o-linear-gradient(#ffffff,#c0c0c0);
!
"onse/uently, most app developers typically use a $
rd
party tool to handle
vendor prefixes and make "## authoring a bit less redundant+ Two of those
products are #ass and 6E##+
9 - 2
2013 Intel Corporation.
Thein!
&bo't Sss
#ass 2#yntactically Awesome #tylesheets4 is an extension of "## that a
allows you to use variables, nested rules, inline imports, with a fully "##*
compatible syntax+ #ass helps keep large stylesheets well*organi,ed, and
get small stylesheets up and running /uickly, particularly with the help of
the "ompass style library+
#ass is essentially a stylesheet compiler+ 7ou author +scss files 2#assy "##4
which are then converted into production*ready "## files by a command*
line utility+
1endor prefixes in #ass are handled through a mechanism called -mixins.
which are analogous to 8avascript functions+ 9owever, whereas a
:ava#cript function typically returns result data based on a set of
parameters, a #ass mixin generates css styles based on passed*in data+
'or instance, the following declaration in #ass:
.m"#u$tom#la$$ {
%include border-radiu$(&'x);
!
)enerates this "## output:
.m"#u$tom#la$${
-webkit-border-radiu$:&'x;
-mo-border-radiu$:&'x;
-m$-border-radiu$:&'x;
-o-border-radiu$:&'x;
border-radiu$:&'x
!
%ore information about #ass is available from www+sass*lang+com+
9 - 3
2013 Intel Corporation.
Fast Track to Intel XDK New
&bo't ()SS
6E## is similar to #ass ; it's a dynamic stylesheet language that's designed
to make "## authoring more robust and easier to maintain+ 6ess is
actually used behind*the*scenes by 5ntel <&0 =ew to manage app styles+
6E## also supports the concept of mixins as illustrated by the following
snippet:
.rounded-corner$ (%radiu$: &'x) {
-webkit-border-radiu$: %radiu$;
-mo-border-radiu$: %radiu$;
-m$-border-radiu$: %radiu$;
-o-border-radiu$: %radiu$;
border-radiu$: %radiu$;
!
#(eader {
.rounded-corner$;
!
#footer {
.rounded-corner$()0'x);
!
)enerated "## code:
#(eader {
-webkit-border-radiu$: &'x;
-mo-border-radiu$: &'x;
-m$-border-radiu$: &'x;
-o-border-radiu$: &'x;
border-radiu$: &'x;
!
#footer {
-webkit-border-radiu$: )0'x;
-mo-border-radiu$: )0'x;
-m$-border-radiu$: )0'x;
-o-border-radiu$: )0'x;
border-radiu$: )0'x;
!
7ou can find out more about 6E## at http:>>lesscss+org
9 - "
2013 Intel Corporation.
Thein!
)nhncing *onts n! T+pogrph+
5ntel i3# webkit browsers supports a large number of fonts, however, very
few of these are also supported by Android's native browser+ To ensure that
your applications uses the same font across a wide variety of devices you
should leverage "##$'s support for downloadable fonts+
)oogle !eb 'onts contains over ?@@ free, open*source fonts that have
been optimi,ed for the web+ Adobe Edge !eb 'onts contains another A@B
fonts+ The most difficult part of implementing web fonts is making a
decision about which fonts to use in your appsC
Downlo!ing *ont
"##$ capable browsers can download fonts and use them to format your
text+ Use the Dfont*face selector to define a font name and associated
download url+ 7ou can then reference the font in subse/uent style
definitions as indicated below:
%font-face {
font-famil": *+roid ,an$*;
$rc: url(font$/+roid_,an$.ttf);
!
(){
font-famil": *+roid ,an$*;
!
C'stomi,ing Te%t Stroke n! *ill Color
"##$ supports the following font*related attributes:
Property Description
text*fill*color #ets the fill color of the text+
text*stroke*color The -outline. color of the text+
text*stroke*width The thickness of the stroke line+
The following snippet illustrates how to use these properties:
-$t"le.
() {
text-fill-color: green;
text-$troke-color: orange;
text-$troke-widt(: /'x;
font-famil": arial;
font-$ie: 00'x;
!
-/$t"le.
-().1(i$ i$ a te$t-/().
9 - #
2013 Intel Corporation.
Fast Track to Intel XDK New
&!!ing Te%t Sh!ows
The "##$ text*shadow property enables you to cast a shadow behind your
text as indicated below:
<style>
p {
font-family:arial;
font-size: 30px;
text-$(adow:/'x /'x &'x #000;
}
</style>
<p>This is a demonstration of text shadows</p>
As illustrated below, text*shadow takes
four arguments:
E+ ight shadow offset
B+ 1ertical 2down4 shadow offset
$+ (lur radius
F+ #hadow color
7ou can visually prototype text*shadow and box*shadow effects by visiting
http:>>css$gen+com>text*shadow> as illustrated in 'igure A+
9 - $
2013 Intel Corporation.
Thein!
&ppl+ing Trnsprenc+
"## $ allows you to
declare colors as ed,
)reen, (lue, and Alpha
transparency+ Alpha
transparency is
specified as a numeric value between ,ero 2fully transparent4 and one
2opa/ue4+ =ote that you should also specify a fallback color to use for
browsers that do not support )(A
-$t"le.
' {
font-famil":arial;
font-$ie: 20'x;
color: rgba(/&&,/&&,/&&,0.0);
text-align: center;
'adding-to': 20'x;
!
#a''etier {
background:url(../image$/a''etier.3'g);
widt(: 04&'x;
(eig(t: )0/'x
!
-/$t"le.
-di5 id67a''etier7.-'.1(i$ i$ a watermark-/'.-/di5.
Creting n -nset.Te%t )$$ect
"ombine color, text*shadow, and rgba transparency to create an insett*
effect as illustrated by the following snippet:
() {
color: #2a)&)& 8im'ortant;
text-$(adow: 0'x )'x rgba(/&&, /&&, /&&, 0.2) 8im'ortant8;
!
9 - %
2013 Intel Corporation.
Fast Track to Intel XDK New
Using )llipsis $or Te%t Over$low
"## $ enables you to automatically terminate text with ellipsis if the
content is too large to fit within its parent container+
<style>
#test {
width: 00px;
hei!ht: "0px;
text-o5erflow: elli'$i$;
w(ite-$'ace: nowra';
o5erflow: (idden;
}
</style>
-di5 id67te$t7.
9orum :'$um and more '$eudo-latin ridiculou$ne$$
-/di5.
-mplementing /ewspper.St+le Col'mns
!ith "##$ it is now relatively straightforward to implement multiple
columns of wrapped text using the column*count and column*gap
properties+ This techni/ue can be particularly useful when developing apps
for tablets+
-$t"le.
#m"article{
column-count: /;
column-ga': )0'x;
/; #olumn-count not im'lemented "et ;/
-mo-column-count: /;
-webkit-column-count: /;
/; #olumn-ga' not im'lemented "et ;/
-mo-column-ga': //'x;
-webkit-column-ga': //'x;
!
-/$t"le.
-di5 id67m"article7.
-'.9orem :'$um...and more latin non$en$e-/'.
-/di5.
9 - &
2013 Intel Corporation.
Thein!
Using 0oogle *onts
As illustrated in 'igure G, )oogle 'onts has a filter panel in its left column
that enables you to search for fonts based on font type 2serif, sans*serif,
display, and handwriting4 as well as thickness, slant, and width+
#tudies have shown that, on mobile devices, sans*serif and display fonts
are more readable than serif fonts+
After you select a font, the )oogle 'onts interface generates the HlinkI
element and font*family css declarations that you'll use to invoke the font
from within your app+ 5t also displays an estimate impact on page load
time+
9 - 9
2013 Intel Corporation.
Fast Track to Intel XDK New
Using &!obe )!ge *onts
Adobe Edge !eb 'onts gives you access to a vast web font library made
possible by contributions from Adobe, )oogle, and designers around the
world+ The fonts are served by Typekit which is a subscription*based
library of hosted, high*/uality fonts that was ac/uired by Adobe in B@EE+
The interface for
selecting fonts from
Adobe Edge is not too
dissimilar from
)oogle 'onts+ 3ne
minor difference is
that while )oogle
uses a HlinkI tag to
download your
selected fonts, Adobe
Edge uses a HscriptI
tag as illustrated by
'igure J+
9 - 10
2013 Intel Corporation.
Figure 9: Load your selected font by including a
<script> tag generated by Adobe Edge Fonts
Thein!
Wlkthro'gh 9.1: &ppl+ing T+pogrph+
5n this walkthrough you will replace the
default font with a )oogle web 'ont+
#elect a web font from )oogle 'onts
#et the custom default font for text in
your application
Apply an -insert. effect to the page
headers
Steps
Open the #roject
E+ 3pen 5ntel <&0 =ew
B+ "lick on the word PROE!"# in the
top*left corner of the )U5+
$+ "lick the Open a Pro$ect button+
F+ #elect the following file:
/ft:ntel<dk=ew/walk/walk>_)/walk>_).xdk
Select 0oogle *ont
A+ 3pen a web browser to )oogle 'onts at:
(tt'://www.google.com/font$
?+ Type the following font name into the text field:
?ambla
G+ "lick the %uic& 'se button+
K+ 5n section E 2"hoose the styles you want4, select (old )**
J+ "opy the HlinkI tag from section $ to your clipboard and note the font*
family declaration in section F+
Deplo+ the 2mbl *ont
E@+ eturn to 5ntel <&0 =ew and open index+html in "ode view
EE+ At the top of the file, where indicated by the comment, paste the
HlinkI tag from your clipboard+
9 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
EB+ 5n the HstyleI block near the top of the file, add a body and paragraph
tag selector that specifies ambla as the font*family and bold as the
font*weight+
bod", ' {
font-famil": *?ambla*, $an$-$erif;
font-weig(t: bold;
!
E$+ #ave the file and test in the Emulator+
C'stomi,e the #ge He!er *ont
EF+ eturn to "ode mode in the index+html file+
EA+ &irectly underneath the style that you added in step EB, define a class
named ui*title that increases the font*si,e for the header text and gives
it an inset effect+ 7our code should appear similar to the following:
.ui-title {
font-$ie: ).&em 8im'ortant;
color: #000000 8im'ortant;
text-$(adow: 0'x )'x rgba(/&&, /&&, /&&, 0.2) 8im'ortant;
!
E?+ #ave the file and test in the emulator+
; End of !alkthrough **
9 - 12
2013 Intel Corporation.
Thein!
)nhncing 3ckgro'n!s
7ou can enhance the backgrounds of images in "##$ by specifiying
background gradients and background images for html elements+ 5f you
plan to use background images, consider base*?F encoding them into your
spreadsheet for improved performance+
&ppl+ing 3ckgro'n! 0r!ient
"##$ gradients enable you to display smooth transitions between two or
more specified colors+ Using gradients offer several advantages over
background images:
)radients reduce download times and bandwidth usage+
)radients automatically ad8ust to running in different screen
resolutions+
)radients retain their integrity ,ooms in or out of an area+
As illustrated by the following snippet, gradient definitions are typically
applied through the background*image css property and re/uire the use of
vendor*prefixes+ The simplest syntax simply deals with direction of the
transformation 2linear, top*bottom4, with a color that's specified for the stop
at @L 2the top of the affected area4 and a color that's the stop at E@@L 2the
bottom of the affected area4+
bod" {
background-image: -webkit-linear-gradient(gold, goldenrod);
background-image: -mo-linear-gradient(gold, goldenrod);
background-image: -m$-linear-gradient(gold, goldenrod);
background-image: -o-linear-gradient(gold, goldenrod);
!
An example of a gradient that transitions from red to white to blue using
color stops is illustrated below:
-$t"le.
bod" {
background-image: -webkit-gradient(
linear, left to', left bottom,
color-$to'(0@,#ffffff),
color-$to'(&0@,#f/0e0e),
color-$to'()00@,#2e/)ff)
);
// ot(er 5endor 'refixe$ omitted for bre5it"
!
-/$t"le.
9 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
%ost designers choose to create gradients visually, and many use the
Ultimate "## )radient generator depicted in 'igure E@+
&ppl+ing 3ckgro'n! -mge
"##$ enables you to scale and position a background image ; two
attributes that are critical for supporting an application that needs to
responds properly to varying screen resolutions+
The basic "## syntax for specifying a background image is the following:
bod" {
background: #000000; // black background color
background-image:url(*image$/beercan.'ng*);
background-re'eat: no-re'eat;
!
Alternately, you can set all background properties in a single statement:
bod" {
background:#000000 url(*image$/beercan.'ng*) no-re'eat;
!
9 - 1"
2013 Intel Corporation.
Thein!
Speci$+ing bckgro'n! si,e
Use the #a$%!ro&nd-size property to scale an image to either a
specified pixel si,e or a percentage of the content area+
7ou can also specify #a$%!ro&nd-size: $o'er; which scales the
background image to completely cover the background area, while
mantaining the background image's aspect ratio+ Using this option may
result in some parts of the background image being hidden+
#pecifying #a$%!ro&nd-size: $ontain; scales the image such that
both the width and the height of the image fit within the content area+
9owever, this may result in the background not being fully covered by the
image+
// $cale t(e background image to co5er t(e bod"
bod"
{
background:url(beercan.gif);
background-$ie: co5er;
background-re'eat:no-re'eat;
!
Speci$+ing bckgro'n!.position
Use the #a$%!ro&nd-position property to set the starting position of a
background image+
1alid settings include the following:
+alue Description
left top
left center
left bottom
right top
right center
right bottom
center top
center center
center bottom
Mositions the background image to a relative location
within its container+
xL yL Mositions the background image to a location specified
as a percentage value along the x>y axis+ The right
bottom corner is E@@L E@@L+
x y Mosition the background at an absolute location,
typically specified in pixels+
9 - 1#
2013 Intel Corporation.
Fast Track to Intel XDK New
3se.45 )nco!ing 3ckgro'n! -mge
(ase*?F encoding enables you to take a binary image file and encode it as a
text string that can be included as part of a stylesheet+ Encoding images
directly into a stylesheet gives you better startup performance since it
eliminates the need for the browser to make separate http re/uests for each
image+ A drawback, however, is that the process usually increases the
image's data si,e by approximately $@L+
!ebsites like www+base?F*image+de provide free services for converting
images to base*?F+
5mages encoded into a stylesheet typically appear as follows 2note that the
image data has been truncated for brevity4:
.bod" {
background-image: url(*data:image/'ng;ba$eA0,iBCD?w66*);
background-$ie: co5er;
background-re'eat: no-re'eat;
!
9 - 1$
2013 Intel Corporation.
Figure ,,: 'se ---.base/01i2age.de to encode your i2ages.
Thein!
Combining M'ltiple 3ckgro'n! -mges
"##$ enables you to specify multiple background images that are stacked
on top of each other as transparency layers+
The following examples illustrate the effect of combining a background
images with a radial gradient to produce a glossy*wood effect:
.ui-(eader-fixed {
background-image: url(*re$ource$/(eaderbackground.'ng*)
!
.ui-(eader-fixed {
background-image: -webkit-linear-gradient(#>f&A/E,#&d/f)4);
!
.ui-(eader-fixed {
background-image: url(*re$ource$/(eaderbackground.'ng*),
-webkit-linear-gradient(#>f&A/E, #&d/f)4) 8im'ortant;
!
Speci$+ing 3ckgro'n! -mges
To specify a background image for all pages in your app, attach a
background*image property to the +ui*page class as illustrated below:
.ui-'age {
background-image: url(*re$ource$/background.'ng*) 8
im'ortant;
background-$ie: co5er 8im'ortant;
background-re'eat:no-re'eat 8im'ortant;
!
To specify a background image for page headers, attach a background*
image property to the +ui*header*fixed class as illustrated in the previous
section+
9 - 1%
2013 Intel Corporation.
Fast Track to Intel XDK New
Wlkthro'gh 9.6: &ppl+ing 3ckgro'n!s
5n this walkthrough you will theme the
header, footer, and body of the app by
applying "##$ techni/ues+
Apply a base*?F encoded background
image to the body of the pages+
Apply a background gradient and image
to the header and footer+
Tweak the style of the control bar
buttons+
Steps
Open the #roject
E+ 3pen 5ntel <&0 =ew
B+ "lick on the word PROE!"# in the
top*left corner of the )U5+
$+ "lick the Open a Pro$ect button+
F+ #elect the following file:
/ft:ntel<dk=ew/walk/walk>_//walk>_/.xdk
Crete /ew St+lesheet
A+ 5n the pro8ect file listing, right*click on the css folder and select =ew
'ile+
?+ ename the new file to custom+css
G+ 3pen the index+html file in code view
K+ !here indicated by the comment, insert a HlinkI element to load the
custom+css file+
&ppl+ 3ckgro'n! to +o'r #ges
J+ 3pen custom+css
E@+ &efine a style class named +ui*page that sets the following properties:
background*image: url2'++>resources>background+png'4N
background*si,e: coverN
EE+ #ave the file and test in the emulator+ 7ou should see that there's now
-beer. in the background in each page of your app+
9 - 1&
2013 Intel Corporation.
Figure ,3: Apply bac&grounds
to t4e 4eader5 body5 and footer.
Thein!
3se.45 )nco!e n -mge
EB+ 3pen a web browser to the following url:
www.ba$eA0-image.de
E$+ "lick the 'pload 62age button+
EF+ Upload the following file:
/ftxdknew/walk/walk>-//re$ource$/background.'ng
EA+ "lick the encode i2age button+
E?+ "opy the background*image property from the "## (ackground 5mage
block onto your clipboard+
EG+ eturn to the custo2.css file+
EK+ Maste the contents of your clipboard into the file, replacing the existing
background*image statement+
EJ+ #ave the file and test the app in the emulator+ 7ou should see that the
background image still appears in the app+
Theme the &ppliction He!er n! *ooter
B@+ eturn to the custom+css file in your editor+
BE+ At the beginning of the file, 5nsert a new class selector named
.ui14eader1fixed that has the following property:
background-image:
url(*../re$ource$/(eaderbackground.'ng*), -webkit-linear-
gradient( #>f&A/E, #&d/f)4) 8im'ortant;
BB+ Add another class selector to the definition that you inserted in the
prior step named .ui1footer1fixed+ 7our code should appear as follows:
(&i-header-fixed) .ui-footer-fixed {
#a$%!ro&nd-ima!e: &rl*+((/reso&r$es/header#a$%!ro&nd(pn!+,)
-we#%it-linear-!radient* #-f./01) #.d0f2, 3important;
}
B$+ #ave the file and test in the emulator+ 7our header and footer should
now have a glossy*wood background+
*ormt the Control 3r
BF+ eturn to the custom+css file+
BA+ At the top of the file insert the following definition to make the button
backgrounds transparent and set the button label style:
.ui-controlgrou'-control$ .ui-btn {
background: tran$'arent;
color: #000000 8im'ortant;
text-$(adow: 0'x )'x rgba(/&&, /&&, /&&, 0.2) 8im'ortant;
border-color: tran$'arent;
!
B?+ #ave the file and test+ =ote that the selected button style class remains
inconsistent with the rest of the footer+
9 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
BG+ eturn to the custo2.css file+
BK+ At the top of the file insert the following definition to make the
selected button style consistent with the rest of the control bar:
.ui-btn.ui-btn-b {
background: tran$'arent 8im'ortant;
border-color: tran$'arent 8im'ortant;
color: #+FF&/0 8im'ortant;
text-$(adow: 0'x )'x rgba()00, )00, )00, 0.2) 8
im'ortant;
!
BJ+ #ave the file and test+ 7our output should appear similar to figure J+
=ote that the list views in the 'riends and (eers list still need to be
themed+
; End of !alkthrough **
9 - 20
2013 Intel Corporation.
Thein!
Working with Theme2oller
Themeoller for 8Ouery %obile is a visual theme designer that enables you
to easily style 8O% U5 widgets+ Themeoller also incorporates
complementary color swatches from Adobe 0uler which can assist you in
selecting complementary colors for your app+
A 8Ouery %obile theme contains global settings for items such as font and
corner radius as well as up to to B? PswatchesP lettered from A*Q, each
with a uni/ue color scheme that can be mixed and matched in your app+
Each swatch sets the colors, textures and font settings for the primary
elements: toolbar, content block and button+ (uttons have $ interaction
states: normal, hover, pressed+
0etting Strte! with Theme2oller
The Themeoller interface has $ ma8or ,ones: the left column contains the
inspector panel, along the top is the Ouick#watch>0uler bar, and below this
is the preview window+
Use the 6nspector panel to set global theme settings on the first tab and
tweak the individual style options for each swatch+
!hen you drag and drop a color from the %uic&#-atc4 panel onto an
element in the preview panel, Themeoller automatically calculates
text color and shadow, borders, gradients and button states+ The sliders
make it easy to ad8ust the lightness and saturation of the colors+ Use
the Adobe 0uler #watches to load complementary color palettes from
Adobe's popular color palette sharing site+
The Pre7ie- panel shows a sample of common 8Ouery %obile
widgets that live update each time you make a change to the theme so
you can /uickly test and tweak the theme+
9 - 21
2013 Intel Corporation.
Figure ,8: $%uery 9obile "4e2eRoller
Fast Track to Intel XDK New
Wlkthro'gh 9.3: Using Theme2oller
5n this walkthrough you will create a custom
stylesheet for your application using 8Ouery
%obile Themeoller+
Use Adobe 0uler to select complementary
colors for your U5 controls
Use Themeoller to generate a "## file
&eploy the custom "## in your app
Steps
Open the #roject
E+ 3pen 5ntel <&0 =ew
B+ "lick on the word PROE!"# in the top*
left corner of the )U5+
$+ "lick the Open a Pro$ect button+
F+ #elect the following file:
/ft:ntel<dk=ew/walk/walk>_2/walk>_2.xdk
Theme 78M Components with Theme2oller
A+ 3pen a browser to http:>>www+8/uerymobile+com>themeroller>
?+ "lick on the :et Rolling button+
G+ "lick on the Adobe ;uler swatches link
K+ "hoose #earc4 !olors from the Adobe 0uler select list+
J+ Enter the following search criteria into the Adobe 0uler search box:
beer
E@+ "lick the searc4 button+
EE+ &rag and drop colors from the various beer color schemes onto the
components in the -A. swatch+
EB+ "lick the Do-nload button+
E$+ Enter a theme name of F<(
EF+ "lick the Do-nload =ip button+
Deplo+ the CSS *ile
EA+ 3pen the ,ip file
E?+ Extract the t4e2es>f-b.css file to the >-al&9?8>css folder+
9 - 22
2013 Intel Corporation.
Figure ,0: 'se "4e2eRoller
to c4ange t4e colors of your
%9 -idgets
Thein!
EG+ eturn to 5ntel <&0 =ew
EK+ 3pen index.4t2l in "ode mode+
EJ+ 5mmediately preceeding the HlinkI tag to custom+css, insert a HlinkI
tag that points to the css>f-b.css file+
B@+ Test your app in the emulator+ =ote that the list of beers and friends are
now themed+
; End of !alkthrough **
9 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit S'mmr+
#ome "##$ style properties re/uire vendor prefixes+
There are a number of $
rd
party tools that you can use to help mitigate
vendor*prefix compatibility issues+
"##$ supports downloadable web fonts+
)oogle and Adobe offer a combined E@@@R fonts freely available for
download+
7ou can combine text*shadow and transparancy effects to output an
inset*text effect+
"##$ enables you to combine background images and gradients to
produce exciting effects+
(ase*?F encode your application's images in order to reduce the
number of http re/uests that must be made and improve app
performance+
7ou can theme your app by overriding 8Ouery %obile "## classes and
by generating a "## file from Themeoller+
9 - 2"
2013 Intel Corporation.
Thein!
Unit 2eview
E+ !hat are the benefits and drawbacks to using base*?F encodingS
B+ 6ist three tools that you can use to either visually prototype "##$
styles or mitigate vendor prefix issues+
$+ !hat are the relative advantages>disadvantages to using ThemeollerS
F+ !hich style class can you override to set a background image for all of
the pages in your appS
9 - 2#
2013 Intel Corporation.
(This page intentionally leIt blank)
Unit 10:
Going into Production
Unit Objectives
After completing this unit, you should be able to:
Configure run permissions on an app
Lock the application into a specific device orientation
Implement a custom icon and splash screen
Create a production build for Android
Install a .apk file on your device
Unit Topics
Creating a Production Build for Android
10 - 1
2013 Intel Corporation.
Fast Track to Intel XDK New
Creating a Production Build for Android
ou!ve made it to the finish line" our app, from all appearances, #orks
great in the simulator and on Intel App Previe#. $o# you!re ready to create
a production build and test it across multiple physical devices and versions
of Android. After you!ve completed device testing, you can upload it to
%oogle Play, the Ama&on App'tore, or simply post it to a #eb server for
do#nload.
our first step is to click on the Build tab in Intel ()* $e# as illustrated
in figure +.
,or Android builds, the overvie# tab #ill indicate that your app is ready to
be packaged into a production-ready .apk file. .o#ever, #hile this is
technically a true statement, there are a number of settings that you #ill
#ant to modify before you proceed #ith packaging.
/he Details panel allo#s you to set your application title, version,
permissions, orientation, and codebase.
/he Assets panel enables you to configure your application!s startup
orientation as #ell as launch icon and startup screens.
/he Plugins panel gives you the ability to upload Cordova plugins for
use in your app.
/he Credentials tab lets you enter credentials for #orking #ith the
,acebook APIs.
/he Push tab configures your app for Push $otification support from
the %oogle Cloud 0essaging 'ervice and Push0obi.
10 - 2
2013 Intel Corporation.
Figure 1: The Overview tab
Going into ro!"ction
Configuring Build Details
Configure the follo#ing information on the )etails tab:
Application Name
/he name of the application that is displayed to the user #hen it!s
installed on the device.
Application Version D
/he version number of the app 1typically +.2 for your initial release3.
Application Permissions
/he device resources that your app uses. $ote that if your app tries to
access a resource for #hich it has not been granted permission, it #ill
usually fail silently.
Device Con!iguration
Choose the devices that you!ll support. ou must select Phone4/ablet
for Android builds.
Operating "#stem
/his #ill default to Android 5.6 #ith back#ards compatibility to
Android 6.7
Code $ase
/here are three options that impact the si&e 1in bytes3 of your build-
%old, Lean, and Lean #ith App %ame Interface. Apps that use
Cordova APIs must choose 8%old9
10 - 3
2013 Intel Corporation.
Figure %: Con!iguring $uild Details
Fast Track to Intel XDK New
Configuring Application Assets
/he Assets tab, depicted in ,igure 7, enables you to add a custom
application icon and splash screens. ou can also set the device!s initial
start-up orientation.
$ote the follo#ing:
/he Android Launch Icon must be a :;<:; P$% file
/he splash screen for phones must be a =62# <+6>2h P$%, ?P%, or
?,I,.
/he tablet splash screen must be a +;22# < 6@;2h P$%, ?P%, or ?,I,
)uring the build process, the launch icon and splash screens #ill be
automatically resi&ed, #hile maintaining the same aspect ratio, to support
different device screen resolutions.
10 - #
2013 Intel Corporation.
Figure &: De!ine a custom icon and splash screen
Going into ro!"ction
oc!ing t"e #creen Orientation
ou can lock rotation using the intel.<dk bridge library by invoking the
follo#ing methods:
Ase the intel.<dk.device.setBotateCrientation1str3 method to the
preferred orientation 18landscape9 or 8portrait93
Ase the intel.<dk.device.setAutoBotate1bool3 method to lock the
orientation.
/he follo#ing code snippet locks an application into a portrait orientation:
<script type="text/javascript">
intel.xdk.device.setRotateOrientation("portrait");
intel.xdk.device.setAutoRotate(alse);
</script>
Adding App Plugins
/he plugins tab, as illustrated in ,igure 5, enables you to create and upload
cordova API e<tensions.
,ull documentation and e<amples for #riting, packaging, and uploading
plugins is located at the follo#ing ABL:
http:DDintel.lyD+dpE+B2
10 - $
2013 Intel Corporation.
Figure ': Adding Cordova Plugins
Fast Track to Intel XDK New
$ntering App Credentials
As depicted in ,igure @, the App Credentials panel is #here you must enter
additional credentials if your app makes use of the Intel ()* native
application ,acebook integration.
0ore information about ,acebook integration is located at the follo#ing
ABL:
http:DDintel.lyD?@ek@C
10 - %
2013 Intel Corporation.
Figure (: Adding Faceboo) Credentials
Going into ro!"ction
Configuring Pus" %otifications
As described in unit =, you #ill need to add information into the Push
notifications panel, in order to receive push notifications from Intel!s
Push0obi service.
10 - &
2013 Intel Corporation.
Figure *: Con!iguring Push+obi support
Fast Track to Intel XDK New
&al!t"roug" 10'1: Pac!aging an App
In this #alkthrough you #ill create a production app for Android devices.
Lock the application device orientation
Configure application permissions
Apload a custom icon and splash page
#teps
Open t"e Project
+. Cpen Intel ()* $e#
6. Click on the #ord P,O-.CT" in the top-left corner of the %AI.
7. Click the Open a Pro/ect button.
5. 'elect the follo#ing file:
/t!ntel"dk#e$/$alk/$alk%&'%/$alk%&'%.xdk
#et a (i)ed Portrait Orientation
@. Cpen inde<.html in Code vie#.
;. At the top of the on)eviceBeady13 function, lock the orientation of the
app into 8portrait9 mode.
intel.xdk.device.setRotateOrientation("portrait");
intel.xdk.device.setAutoRotate(alse);
=. 'ave the file.
Configure Android Per*issions
>. Click on the $uild tab
:. Click on the Android $uild button.
+2. Click the 0pload Code button.
++. Click on )etails and configure the follo#ing properties:
Application /itle: ,riends#ithBeer
Application Fersion $ame: +.2
/his app uses geolocation: es
/his app accesses the user!s contacts: es
10 - '
2013 Intel Corporation.
Going into ro!"ction
Upload an +con and #plas" Page
+6. Click the bro#se button adEacent to the Android Launch Icon field.
+7. 'elect the #alk+2G+DresourcesDicon.png file.
+5. Click the bro#se button adEacent to the Phone 'plash 'creen field.
+@. 'elect the #alk+2G+DresourcesDsplash.png file.
Create a Build
+;. Click on the Overview tab.
+=. Click the $uild App Now button.
+>. Click the Download $uild button and save the file to your computer.
Test t"e Build
+:. Hmail the .apk file to yourself.
62. Cpen the mail client on your Android phone.
6+. Cpen the email that contains your .apk file.
66. Cpen the apk file on your device, install, and test it.
Hnd of Ialkthrough J
10 - (
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit #u**ar,
Accessing some hard#are functions reKuire that you grant permissions
to your app.
Application icons and startup images are automatically resi&ed during
the build process in order to support multiple device resolutions.
Ase the intel.<dk.device methods to lock the application into using a
specific orientation.
,acebook and Push notification support reKuire that you enter
additional credentials during the build process.
ou can email .apk files to your users or post them to a #eb server.
App distribution does not reKuire uploading your app to %oogle Play.
Al#ays test your app on a physical device prior to uploading it to an
app store.
10 - 10
2013 Intel Corporation.
Going into ro!"ction
Unit -evie.
+. Ihich device resource permissions can be set #ithin the Build
processL
6. Ihat is a plugin and #hy #ould you need oneL
7. App icons and splash screens are automatically scaled in order to
account for varying device resolutions.
5. )escribe the process for installing an .apk file on a physical device.
10 - 11
2013 Intel Corporation.