This chapter will give you an introduction to Sencha Touch, the framework, the platform, and its developer experience. It will take you through the required steps to install the tools in your workstation and will guide you through the creation of your first basic applications.
Sencha Touch is an MVC JavaScript framework specially designed to create mobile web applications for touchscreen devices. Sencha Touch allows developers to create applications for mobile platforms that feature web browsers implementing the latest standards, like the WebKit browser engine.
Note
At the time of this writing, the latest available version of Sencha Touch was version 2.1.
Sencha Touch is a rather large framework, which may look daunting to JavaScript developers used to smaller, leaner libraries such as jQuery or Prototype. Sencha Touch is conceived as a whole package, including most services and functions offered by other frameworks, and it can be easily extended in many different ways to accommodate the needs of developers in different areas of expertise. You typically do not need to use other libraries than Sencha Touch in your project; if you need a certain utility, you can be sure that the framework includes it by default.
The explicit choice of WebKit is an interesting one; the Sencha Touch team has taken a deliberate decision not to support other mobile browser engines, such as Gecko (Firefox), Presto (Opera), or Trident (Internet Explorer). The exclusive support of modern browsers allows Sencha Touch to use many of the most advanced web technologies available today.
This choice also affects the developer experience, because only Safari or Google Chrome can be used to debug Sencha Touch applications on a desktop environment like Linux, Windows, or OS X.
Internet Explorer 10 support
The Sencha team has recently announced the support for Internet Explorer 10 for Windows Phone 8 in Sencha Touch 2.2, not yet available at the time of this writing.
Apple, in one of the first versions of its iOS design guidelines document, famously stated that there are three major kinds of mobile applications that could be created for the iPhone:
- Utility apps, like weather or stocks information apps
- Productivity apps, like business or document-oriented applications
- Immersive apps, like games
Following this simple taxonomy, Sencha Touch is most suited for delivering applications of the first two kinds. Although it is certainly possible to create games or other types of apps featuring complex user experiences, this book covers only the creation of utility and productivity applications.
Finally, Sencha Touch allows developers to create applications for mobile touchscreen devices—that is, smartphones and tablets—but it can be used to create desktop applications as well.
Back in 2005, the Web 2.0 movement was starting to radically transform the notion of web content. Ajax-enabled sites like Gmail showed the public that a new type of interaction was possible, that a new kind of content could be shown in regular web pages without using proprietary plug-ins. Douglas Crockford was explaining that JavaScript was a great language misunderstood by many, and libraries like script.aculo.us and Prototype were offering developers concrete and solid grounds for cross-browser masterpieces.
Amidst all the fuss, Yahoo! released the first version of its YUI library, allowing developers to create complex, “desktop-like” applications across operating systems and browsers. YUI can be considered a seminal work, after which several other libraries appeared through the years.
Around that time, Jack Slocum started working on a set of extensions for YUI called YUI-Ext. After a couple of releases, the interest in his library grew so much that he removed the requirement of YUI altogether, making the library able to use Prototype or YUI for lower-level cross-browser compatibility.
Ext JS was born. For years, Ext JS set the standard in terms of cross-browser compatibility and design, allowing developers to create complex browser applications in a fraction of the time, and without having to care about browser incompatibility problems. In 2009, the company behind Ext JS incorporated as Sencha Inc., with headquarters in Redwood City, California.
In 2009, the rise of the touchscreen smartphone and, later, the iPad, prompted the Ext JS team to create a version of the framework geared exclusively for these new devices; the result of their efforts is Sencha Touch, released in version 1.0 at the end of 2010.
The first version of Sencha Touch was not completely compatible with the contemporary version of Ext JS, and it was also criticized for its relatively low performance benchmarks, particularly in old devices such as the iPhone 3G. To address these issues, Sencha Touch 2 was released in March 2012, providing a brand-new rendering engine based 100% on Cascading Style Sheets (CSS), and a new class system compatible with Ext JS 4.
Sencha Touch is more than just a full-featured framework geared toward the creation of utilities and productivity applications; it is actually a complete enterprise web application platform, with the following characteristics:
- Large UI library widget, largely inspired by iOS, both in design and functionality
- Fast rendering engine based on CSS, which can be hardware-accelerated in the latest mobile devices
- Well-defined architecture, enforcing the MVC architecture from the very beginning
- Built-in connectors for network data services, such as Representational State Tranfer (REST) web services, and support for offline mobile web applications
- Advanced class-loading mechanism, enforcing naming guidelines and the MVC architecture
- A command-line build system, managing merging and minification of application code, as well as building native applications for Android and iOS
- Extensive documentation, available as a set of dynamic HTML pages, including searching and filtering features without requiring any server-side infrastructure
Sencha Touch can be seen as an “all-in-one” framework, including all the APIs and tools required to create your mobile applications.
Sencha Touch, at the moment of this writing, supports only the following mobile platforms:
- iOS since version 3
- Android since version 2.3
- BlackBerry OS since version 6 (only for devices featuring WebKit-powered browsers)
Furthermore, the Sencha Touch team has announced the upcoming availability of support for Windows Phone 8 in 2013, as well as a preliminary version of a theme for BlackBerry 10.
Sencha Touch is a 100% browser-based framework, and as such it is server-agnostic; you can deploy your Sencha Touch applications using any server-side technology, like PHP, Java, Ruby on Rails, .NET, or any other stack of your choice.
Sencha Touch 2.1 Exclusively
This book will deal exclusively with the APIs and features of Sencha Touch 2.1, without making any references to the characteristics of previous versions of this framework.
Sencha Touch is available under a quite complex licensing scheme; at the time of this writing, developers can use the framework as follows.
On open source projects:
On commercial projects:
- You can use Sencha Touch for free, without any fees, either per application, per user or per developer.
- For embedded applications, you can use Sencha Touch for free up to 5,000 installations.
- Finally, a commercial OEM license is available as well, for companies willing to distribute Sencha Touch as part of their own commercial applications or services.
Sencha Touch is also distributed and licensed as part of the “Sencha Complete” package, which includes the following:
To create applications with Sencha Touch, you need the following tools, many of those part of the standard web developer toolkit:
- A computer running Linux, OS X, or Windows
- Google Chrome or Apple Safari
- A text editor
- The Sencha Touch framework
- A working Ruby and RubyGems installation
And that is pretty much everything you need to start with. Of course, Sencha Touch being a mobile framework, you might want to have either the Android or the iOS software development kit (SDK), both available for free from Google and Apple respectively. And, last but not least, a mobile device, running iOS or Android, in order to test your applications on the device. For the moment you do not need the mobile device or the SDK; although handy, you can just use your desktop browser (based on WebKit) to run the application as is.
Other tools are recommended to accelerate your developer workflow. In particular, the example code of this book was written on a Mac running OS X Mountain Lion, plus some other tools:
- iOS Simulator bundled with Xcode 4.5 (available for free in the Mac App Store)
- Homebrew
- Google Chrome
- iTerm2, Zsh, oh-my-zsh, and tmux
- Vim and MacVim with the Janus plug-in distribution
- LiveReload
- MAMP Pro
- iOS devices (iPhone and iPad)
The combination of MacVim (plus the JavaScriptLint plug-in) and LiveReload are huge boosters to productivity, but of course your mileage may vary.
Of course, the next thing you need is the actual Sencha Touch library. If you go to the Sencha website, you can get a ZIP file directly from the home page; however, pay attention to the fact that you are going to be asked about the license for your project. In this case, we are going to browse the official download page of Sencha Touch to get the GPLv3 version, the one we are going to use throughout this book to show examples.
Installation script
The source code of the
application, available in Github, contains a script (install.sh
) for Unix
systems, which automatically downloads and installs the required libraries for
the samples to work.
Once downloaded, open the ZIP file; inside you will have several different folders. The most important are the following ones:
-
Several JavaScript files are available in the root of the distribution folder:
Among them,
sencha-touch-all-debug.js
andsencha-touch-all.js
are the most important, used during both development and production. The biggest difference between them is that the-debug
version is not minified, which makes it easier to pinpoint and troubleshoot errors in your applications as you develop them. -
The
docs
folder contains a complete documentation system, ready to use, available offline for your perusal; later in this chapter we are going to describe in detail the different features of this documentation system. -
The
examples
folder contains lots of sample applications built with Sencha Touch, each showcasing a particular aspect of the framework. It is strongly recommended to try them all, particularly the Kitchen Sink application (located inexamples/kitchensink
), which is a complete demo of all the widgets available in the Sencha Touch framework. -
The
resources
folder contains not only pre-built CSS files and images provided by the framework, but also the complete list of SASS source files used to generate those CSS styles. In a later chapter we are going to study in detail how to customize your Sencha Touch application, creating your own styles for your applications. -
Finally, the
src
folder contains the original JavaScript source files of the Sencha Touch framework, used to generate the final, minified JavaScript files that you will actually use to power your own apps.
Another optional component that can be installed is Sencha Cmd, which consists of command line tools that can be used to create and update Sencha Touch applications from a terminal.
The Sencha Cmd distribution can be downloaded from the same official download page of Sencha Touch. It requires a working Java installation in your workstation.
Note
At the time of this writing, the current version of Sencha Cmd was version 3.0.0.250.
After downloading Sencha Cmd, unzip the distribution file and execute the installer; Figure 1-1 shows the installer for OS X.
After you have installed the Sencha Cmd tools, make sure to update your PATH
variable to point to the default location where the Sencha Cmd tools are
installed:
~/bin/Sencha/Cmd/3.0.0.250
Mountain Lion and Java
The latest version of OS X at the time of this writing, Mountain Lion, does
not include a Java Runtime Environment by default, and the Sencha Cmd Tools
installer requires one to execute. You can force the installation of the latest
JRE very easily by running java -version
on a command line; this will prompt
OS X to download and install it.
To make sure the installation went well, open a terminal window and type
the sencha
command; you should see an output similar to the following:
Sencha Cmd v3.0.0.250 Options * --debug, -d - Sets log level to higher verbosity * --plain, -p - enables plain logging output (no highlighting) * --quiet, -q - Sets log level to warnings and errors only * --sdk-path, -s - sets the path to the target framework Categories * app - Perform various application build processes * compile - Compile sources to produce concatenated output and metadata * fs - A set of useful utility actions to work with files. * generate - Generates models, controllers, etc. or an entire application * manifest - Extract class metadata * package - Packages a Sencha Touch application for native app stores * theme - Builds a set of theme images from a given html page Commands * ant - Invoke Ant with helpful properties back to Sencha Command * build - Builds a project from a JSB3 file. * config - Loads a config file or sets a configuration property * help - Displays help for commands * js - Executes arbitrary JavaScript file(s) * which - Displays the path to the current version of Sencha Cmd
We are going to use this tool later in this chapter; for the moment, let us see how to create a new application manually.
We are going to start our journey of discovery of Sencha Touch by creating the simplest possible application that you could create with it: a canonical “Hello, World!” application. It will have the following features:
- It will include all the required icons and default images supported by iOS and Android.
- It will use the most minimal index.html file possible.
The most basic Sencha Touch application consists, at least, of the following:
- The Sencha Touch libraries (which we have downloaded in the previous section)
- An index.html file
- One JavaScript file containing the source code of your application, which we will usually refer to in this book as app.js
Let’s begin with index.html:
<!DOCTYPE html>
<html>
<head>
<meta
charset=
"utf-8"
/>
<title>
Hello World</title>
<!-- Load Sencha Touch -->
<link
rel=
"stylesheet"
href=
"/_libs/sencha/resources/css/
sencha-touch.css"
/>
<script
src=
"/_libs/sencha/sencha-touch-all-debug.js"
></script>
<!-- Load our code -->
<script
src=
"app.js"
></script>
</head>
<body>
</body>
</html>
As you can see, this is the most bare-bones HTML5 file you could expect; it just specifies the encoding of the page, its title, and loads both the JavaScript and the CSS included in the Sencha Touch distribution. Finally, we load our own app.js JavaScript file, where the fun happens.
Do not forget the <body> tag!
Do not forget to add an opening and closing set of <body></body>
tags, as
otherwise your application might not appear on the screen. Sencha Touch
manipulates the root element of the body
tag to generate the required tags for
the UI to appear on the screen.
Let’s see now how the JavaScript file must be:
Ext
.
application
({
name
:
'HelloWorld'
,
launch
:
function
()
{
// This is where the fun starts!
}
});
At this stage, if you navigate to your file index.html
using Safari or Chrome,
you will be able to see an empty screen appear. If you use the web inspector
provided by those browsers, you should not have any errors or warnings
displayed. Not the best feedback, but we are going to add more personality to
our application soon.
Every Sencha Touch application has at least the structure shown above, starting
with the most important element, a call to the Ext.application()
function,
which takes a literal object as parameter.
This is a very common idiom in Sencha Touch; many functions are built in such a way that the developer has to pass only a literal object, usually also referred to as a dictionary, as the only parameter. We are going to see this pattern all over the framework:
Ext
.
someFunction
({
parameter1
:
'value1'
,
parameter2
:
false
});
The following technique will help you avoid typing errors or problems with unfinished dictionaries:
Commas vs. semicolons
Remember that inside the curly brackets, the parameters are separated by commas, and not by semicolons. Using a “JavaScript Lint” tool in your editor will allow you to catch these and other common typing errors every time you save the file.
The call to the Ext.application()
function takes as its sole parameter an
object with two very important keys:
-
name
: This property is of type string and provides the root namespace for all the objects contained inside the application. Sencha Touch creates this namespace automatically for the developer, and this name will be used throughout the application to scope all objects and avoid cluttering the global namespace. -
launch
: This property expects a function that will be executed when the framework code has been loaded and the application is ready to execute.
For all practical purposes, the launch
function is the de facto entry point of
your application; it is the location where the developer starts writing his own
code, and begins providing personality and style to the app. For example, the
following application will display an alert window when the application starts:
Ext
.
application
({
name
:
'HelloWorld'
,
launch
:
function
()
{
Ext
.
Msg
.
alert
(
'Application launched'
);
}
});
You can see the result of the code in Figure 1-2.
Note
iOS developers might find it useful to think about the object passed as
parameter of the Ext.application()
function as the “application delegate” that
is so common in the mobile operating system created by Apple.
What other parameters can be passed to the Ext.application()
function? There
are many of them, as shown in the following snippet:
Ext
.
application
({
name
:
'HelloWorld'
,
appFolder
:
'app'
,
profiles
:
[
'Phone'
,
'Tablet'
,
'Desktop'
],
icon
:
{
57
:
'img/Icon.png'
,
72
:
'img/Icon-iPad.png'
,
114
:
'img/Icon@2x.png'
,
// Retina iPhone
144
:
'img/Icon-iPad@2x.png'
// Retina iPad
},
startupImage
:
{
'320x460'
:
'img/Default.png'
,
'640x920'
:
'img/Default@2x.png'
,
// Retina iPhone
'768x1004'
:
'img/Default-Portrait.png'
,
'748x1024'
:
'img/Default-Landscape.png'
,
'1536x2008'
:
'img/Default-Portrait@2x.png'
,
// Retina iPad, Portrait
'1496x2048'
:
'img/Default-Landscape@2x.png'
// Retina iPad, Landscape
},
models
:
[],
views
:
[],
controllers
:
[],
fullscreen
:
true
,
isIconPrecomposed
:
true
,
statusBarStyle
:
'black'
,
// can also be 'default'
launch
:
function
()
{
Ext
.
Msg
.
alert
(
'Application launched'
);
}
});
-
appFolder
specifies an alternative location for the files of the application; by default, Sencha Touch loads automatically, on demand, the files located in anapp
folder, at the same level as theindex.html
file. -
profiles
allows the application to become “universal,” that is, to feature different user interfaces (UIs) for different supports. Sencha Touch supports three different profiles, for phones, tablets, and desktop browsers. Using profiles, a developer can create customized UIs for different devices, sharing the same controllers and low-level logic. Profiles are explained in detail in Chapter 10. -
icon
takes a dictionary of number-string pairs; the number represents the size in pixels of the expected icon, and the string attached to the number is the relative location of the associated icon file. -
startupImage
takes a dictionary as parameter, with keys representing the widths and heights of different iOS devices. The values of this dictionary are the paths to the corresponding startup images shown by iOS when the user opens a web application saved on the home screen. -
models
,views
, andcontrollers
hold arrays of class names to be loaded automatically by Sencha Touch. -
isIconPrecomposed
specifies whether the icon of the application, when saved on the home screen of an iOS device, receives the typical shading provided by the operating system. -
Finally,
statusBarStyle
specifies the type of status bar (black, default, or translucent) to be shown on top of the application when running on an iPhone or an iPod Touch device.
Using the information in the keys above, such as icon
and startupImage
,
Sencha Touch generates the required <meta>
tags in the DOM of the browser, as
shown in Figure 1-3.
Let us see now how to create a simple Sencha Touch application using the command-line tools.
Note
This section requires you to have the Sencha Cmd tools installed. Please refer to Installing Sencha Cmd for more information.
The first thing to do is to open a terminal window and, assuming that the
Sencha Touch folder is located inside the _libs
folder (as is the case for
the source code of this book), type the following command:
$ sencha -sdk _libs/sencha generate app NewApp ./NewAppFolder
The sencha generate app
command takes two parameters: the name of the app (in
this case NewApp
) and the location (in this case, the NewAppFolder
, which is
a subfolder of the current location). The -sdk
switch specifies the location
(anywhere in the disk) of the Sencha Touch distribution (namely, the folder
created when the ZIP file is unzipped.)
The terminal window will show the following output (edited for brevity):
Sencha Cmd v3.0.0.250 [INF] init-properties: [INF] init-sencha-command: [INF] init: [INF] -before-generate-workspace: [INF] generate-workspace-impl: [WRN] Ignoring @require ../version/Version.js in js/String.js [WRN] Ignoring @require ../Ext-more.js in js/Format.js [INF] -before-copy-framework-to-workspace: [INF] copy-framework-to-workspace-impl: [INF] [copy] Copying 1103 files to NewApp/touch [INF] [copy] Copied 171 empty directories to 1 empty directory under NewApp/touch [INF] [copy] Copying 1 file to NewApp/touch [INF] [copy] Copying 1 file to NewApp/touch [INF] [propertyfile] Updating property file: NewApp/.sencha/workspace/sencha.cfg [...SNIP...] [INF] generate-app:
Finally, if you open your browser and navigate to the web application that has just been generated, you will see an output similar to that of Figure 1-4.
Note
As mentioned in the preface of this book, please be aware that Sencha Touch
applications use the XMLHTTPRequest
object extensively and that opening your
HTML files directly (that is, using the file:///
protocol) does not work; you
should use a local web server instead.
Sencha Cmd provides many other services, which we will see in detail in
Chapter 10. For the moment, suffice to say that the sencha
command
builds an application that conforms to the MVC standard enforced by Sencha
Touch.
Sencha Touch comes bundled with a long list of components, objects, functions, and code ready to use out of the box. This class library is comparable with the ones bundled with the Java or .NET runtimes, and provides nearly all the basic blocks to create complex applications rapidly.
Not only that, but these classes are also built upon the principle of the MVC architecture, each of them fitting in a particular layer of a more complex architecture.
The Sencha Touch 2 class library includes the following families of classes:
- Model classes, providing developers with the means of describing the business entities that are ultimately managed, created, edited, and destroyed by your own applications. These classes are described independently of the storage medium required, be it remote or local, based upon JSON or XML. Chapter 4 provides more information about this subject.
-
Communication classes, describing both the storage and communication
strategies to be used when creating new applications. The most important
classes in this family are
Store
,Proxy
, andReader
, which provide common abstractions allowing applications to consume data from remote web services or to store information locally on the host browser. - Views, which are used to easily build the user interface of any application with a consistent set of patterns; these are the most visible parts of the application and can use the advanced hardware acceleration capabilities of modern mobile devices to render themselves as quickly as possible, using CSS exclusively. Chapter 3 describes this family of classes in detail, showing examples of how to use the most important view components in your applications.
- Controller classes provide the glue between views and models, centralizing all the interaction in specialized classes, which hold the most important parts of the logic of the application. Controllers allow developers to organize their code in useful and reusable components, separating the business logic from the UI, and providing a more maintainable architecture for applications. Chapter 6 dives into this family in detail, showing all the advantages of using controllers in your own applications.
- Utility classes are pervasive in the framework and provide a tremendous amount of ready-to-use code, ranging from date and number formatters, containers, proxies, and many other classes.
The following chapters will deal with each of these families in detail.
The usual data structure used to represent the in-memory structure of objects
embedded into a user interface is the tree; this is very easy to achieve in
Sencha Touch, thanks to one of the most important properties of any visual
component: the items
property.
The items
property (available in subclasses of the Ext.Container
class)
takes an array of widgets ready to be embedded as children to the current
component. For example:
Ext
.
define
(
'BookApp.view.CustomList'
,
{
extend
:
'Ext.dataview.List'
,
config
:
{
items
:
[{
xtype
:
'toolbar'
,
title
:
'To Do List'
,
items
:
[{
xtype
:
'spacer'
},
{
xtype
:
'button'
,
iconCls
:
'add'
,
ui
:
'plain'
}]
}]
}
});
Analogies with other mobile platforms
For iOS developers, you can think of the items
property as the Sencha Touch
equivalent of the addSubview:
method. In the case of Android, the equivalent
API would be the addView()
method of the View
class. The biggest difference
in the case of Sencha Touch is that the items
property takes an array of
views as parameter, while the APIs of both iOS and Android take individual view
instances as parameters.
However, a basic question remains: How does the parent component know how to embed the children component, particularly regarding its location on the screen? It turns out that many components are actually expected to be located in precise parts of the screen, like toolbars or navigation bars; in those cases, the component will be displayed exactly at the required location, without requiring further intervention from the developer.
For most components, however, it is required to specify the location of the
child component in its parent; in those cases, you can add a layout
parameter to the parent view, and then Sencha Touch will position the child
objects accordingly to their respective orders in the items
array.
Layouts will be described in great detail in Chapter 3.
Most Sencha Touch user interface components are able to react to user events, and developers can attach functions to be executed every time one of these events is triggered.
It is very simple to attach functions as event handlers: The only thing that is
required is to specify a listeners
configuration element to your user
interface object.
Ext
.
Viewport
.
add
({
xtype
:
'panel'
,
items
:
[{
xtype
:
'toolbar'
,
docked
:
'top'
,
items
:
[{
xtype
:
'button'
,
text
:
'Show alert'
,
listeners
:
{
tap
:
function
(
button
,
e
,
eOpts
)
{
Ext
.
Msg
.
alert
(
'Event triggered'
);
}
}
}]
}]
});
In the example above, the button in the toolbar is able to react to the tap
event, which is one of the simplest events found in Sencha Touch. This event
triggers the execution of the corresponding function, which takes a certain
number of parameters; the Sencha Touch documentation, described in the next
section, provides the exact definition of the parameters required in every one
of the events exposed by the framework. Events will be described in more detail
in Chapter 3.
However, attaching event handlers to view components using this approach can
quickly lead to unmaintainable and/or non-reusable code, which somehow breaks
the MVC architecture, as the business logic is intertwined with the view logic.
Sencha Touch allows developers to centralize business logic and event handlers
in controller classes, inheriting from Ext.app.Controller
. This approach will
be explained in Chapter 6.
As mentioned before, the Sencha Touch distribution contains the entire API
documentation that is available on the website; this makes it very easy to use
and to refer to by developers, who can access this invaluable information even
when offline. To open it, just double-click the docs/index.html
file in
your Sencha Touch distribution folder; Figure 1-5 shows the
contents of the documentation when they are opened for the first time.
The Sencha Touch documentation is bundled as an HTML5 application that uses the local storage of your browser to remember which tabs were open during your last session. This way, you will always find your way and, should you inadvertently close the browser window, the same pages will be opened for you the next time you access the documentation, as shown in Figure 1-6.
Another handy feature of the built-in documentation system is integrated, full-text client-side search; type any text on the search field on the top right of the documentation browser, and you will be able to find your way. You can type any kind of API, function, even xtypes; all of them are just a keystroke away. Figure 1-7 shows how this brilliant search system works.
It’s a good idea to have this documentation system open at all times, whenever you are writing your Sencha Touch applications; the amount of information contained in it is invaluable. Even better, as we will learn in Chapter 8, you can generate the same kind of documentation for your own projects!
This chapter has shown you how to download the Sencha Touch distribution, and how to write and understand the basic principles of every application created with the framework. The next chapters will explore in depth different aspects of Sencha Touch, used to create very complex applications.
Get Sencha Touch 2 Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.