Sencha Touch - Quick Guide



Sencha Touch - Overview

Sencha Touch is a popular framework of Sencha for creating a user interface for mobile applications. It helps the developer create a mobile app using simple HTML, CSS, JS which supports many mobile devices such as android, IOS, BlackBerry, and Windows. It is based on MVC architecture. The latest version of Sencha Touch is 2.4.

History of Sencha Touch

After releasing Sencha's other product, ExtJs, which was for web application, there was a need to develop a framework which works on mobile devices too.

The first version of Sencha Touch was 0.9 beta version, which supported Android and IOS devices. Later, the first main release of Sencha Touch version 1.0 was in November 2010, which was the first stable version and supported Blackberry devices too.

The latest release of Sencha Touch is version 2.4 released in June 2015, which supports many devices such as Windows, Tizen along with Android, IOS, BlackBerry OS 10, Google Chrome for Android and mobile Safari, etc.

Features of Sencha Touch

Following are the most prominent features of Sencha Touch −

  • Customizable and more than 50 build in UI widgets with a collection of rich UI such as lists, carousels, forms, menus, and toolbars, built specifically for mobile platforms.

  • Code compatibility of new versions with the older one.

  • A flexible layout manager that helps organize the display of data and content across multiple mobile devices with different OS.

  • The framework includes a robust data package that can consume data from any backend data source.

  • Adaptive layouts, animations, and smooth scrolling for a better mobile web application experience for the use.

  • Out-of-the-box, native-looking themes for every major platform enables to make web and hybrid applications match the look and feel of the target platforms.

Sencha Touch ─ Benefits

Sencha Touch is the leading standard for business-grade web application development. It offers the tools necessary to build robust applications for most of the mobile devices providing a single platform for developing applications. Following are some of the benefits −

  • Provides a responsive touch feature, hence the user can easily navigate while using the mobile app.

  • Provides compatibility with all the latest versions of IOS, Android and Blackberry, and Windows.

  • Provides fastest possible speed desirable for any mobile application.

  • Provides a cost-effective solution with its cross-platform compatibility.

  • Based on the native APIs and basic web development languages such as HTML, CSS, JS which makes it easier for a developer to understand Sencha Touch.

Sencha Touch ─ Limitations

Sencha Touch API doesn't have the following capability −

  • The app does not have access to the device’s camera, contacts, and accelerometer.

  • It does not provide the push notification facility. For this, we have to use websockets or long polling.

  • According to general public license policy, it is free for open source applications however paid for commercial applications.

  • It is not good for hardcore graphics and animation apps such as for gaming apps.

Sencha Touch ─ Tools

Sencha SDK

This is Sencha development kit used to create a skeleton of the project. We use the command "sencha -sdk path/to/touch generate app appName" to create an app with the name given in the command.

When the app is created, you can see the following files in the app −

  • app − This folder contains model, view, controller and store files for the app.

  • app.js − This is the main JS file for your application. From this file, the Sencha code flow starts.

  • app.json − This is the configuration file for the app, all the configuration details presents here.

  • index.html − This is the main html file where we include the app.js and other Sencha related files.

  • package.json − This file has all the dependency and other information related to the app.

  • resources − This folder includes all the CSS files and images required for the application.

Sencha CMD

Sencha CMD is a command line tool, which provides the features of Sencha Touch code minification, scaffolding, build generation, and other useful features for production purpose.

We use command "Sencha app build package" in the command prompt to build the application for this. Go to the app directory in the command prompt and type the above command. Once the build is successful, we will see the minified version of the application basically used for production purpose.

This can be downloaded from https://www.sencha.com/products/extjs/cmd-download/

Sencha Inspector

Sencha Inspector is a debugging tool to debug any issue in Sencha code during development.

Sencha Touch - Environment Setup

We have set up Sencha Touch Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

<!DOCTYPE html>
<html>
   <head>
      <link href="http://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
      <script type="text/javascript" src="http://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type="text/javascript">
        Ext.application({
           name: 'Sencha',
           launch: function() {
              Ext.create("Ext.tab.Panel", {
                 fullscreen: true,
                 items: [{
                    title: 'Home',
                    iconCls: 'home',
                    html: 'Welcome'
                 }]
              });
           }
        });
      </script>
   </head>
   <body>
   </body>
</html>

Local Environment Setup

This section guides you on how to download and set up sench Touch on your machine. Please follow the steps to set up the environment.

Downloading library files

Download a commercial version of Sencha Touch library files from sencha https://www.sencha.com. You will get the trial version from the site on your registered mail id which will be a zipped folder named sencha-touch-2.4.2-commercial.

Unzip the folder and you will find various JavaScript and CSS files which you will include in our application. We will mostly include following files:

(1) Javascript Files JS file which you can find under folder \sencha-touch-2.4.2-commercial\touch-2.4.2 are :

File and Description
sencha-touch.js
This is the core file which contains all functionality to run the application.
sencha-touch-all.js
This file contains all the code minified with no comments in the file
sencha-touch-debug.js
This is the unminified version of sencha-touch-all.js for debugging purpose.
sencha-touch-all-debug.js
This file is also unminified and is used for development purpose as it contains all the comments and console logs also to check any errors/issue

You can add these files to your projects JS folder or you can give direct path where the file reside in your system.

(2) CSS Files There are number of theme based files which you can find under folder I:\sencha touch\sencha-touch-2.4.2-commercial\touch-2.4.2\resources\css\sencha-touch.css

These library files will be added in an Sencha Touch application as follows:

<html>
   <head>
    <script type="text/javascript" src="../sencha-touch-2.4.2-commercial/touch-2.4.2/sencha-touch-all.js"></script>  
    <link href="../sencha-touch-2.4.2-commercial/touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
    <script type ="text/javascript" src = "app.js" > </script> 
   </head>
</html>

You will keep sencha Touch application code in app.js file.

CDN setup

CDN is content delivery network with which you do not need to download the Sencha touch library files instead you can directly add CDN link for ExtJS to your program as follows:

<html>
   <head>
    <script type="text/javascript" src="http://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>    
    <link href="http://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
    <script type ="text/javascript" src = "app.js" > </script> 
   </head>
</html>

Popular Editors

As it is a JavaScript framework which is used for developing web applications, in our project we will have HTML, JS files and to write your Ext JS programs, you will need a text editor. There are even multiple IDEs available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), Notepad++.
  • Brackets: is another popular IDE which can be downloaded from http://brackets.io/ .
  • Sublime: is another popular IDE which can be downloaded from https://www.sublimetext.com/3/ .

Sencha Touch - Naming Convention

Naming convention is a set of rules to be followed for identifiers. It makes the code easily readable and understandable for other programmers as well.

Naming convention in Sencha Touch follows the standard JavaScript convention, which is not mandatory but a good practice to follow. It should follow camel case syntax for naming the class, method, variable, and properties.

If the name is combined with two words, the second word will start with an uppercase letter always. For example, doLayout(), StudentForm, firstName, etc.

Sr.No. Name & Convention
1

Class Name

It should start with an uppercase letter, followed by camel case. For example, StudentClass

2

Method Name

It should start with a lowercase letter, followed by camel case. For example, studentMethod()

3

Variable Name

It should start with a lowercase letter, followed by camel case. For example, studentName

4

Constant Name

It should be in uppercase only. For example, COUNT, MAX_VALUE

5

Property Name

It should start with a lowercase letter, followed by camel case. For example, enableColumnResize = true

Sencha Touch - Architecture

The bottom layer for any mobile application is OS, on top of that anything or everything is built. Then we have the browsers on which we will be running the applications. It could be Chrome, Safari, IE anything. The upper layer is a W3 standards, which is common for all. Sencha Touch stands or is built on top of W3 standards, which is nothing but HTML5, which makes a single application compatible with different browsers of different devices.

Sencha Touch is a combination of three frameworks − ExtJs, JqTouch, and Raphael (vector drawing). It follows MVC architecture. MVC separates the code into more manageable chunks.

Although the architecture is not mandatory for the program, however, it is a best practice to follow this structure to make your code highly maintainable and organized.

Project Structure With Sencha Touch App

----------src
----------resources
-------------------CSS files
-------------------Images
----------JavaScript
--------------------App Folder
-------------------------------Controller
------------------------------------Contoller.js
-------------------------------Model
------------------------------------Model.js
-------------------------------Store
------------------------------------Store.js
-------------------------------View
------------------------------------View.js
-------------------------------Utils
------------------------------------Utils.js
--------------------------------app.js
-----------HTML files

Sencha Touch app folder will reside in the JavaScript folder of your project.

The App will contain controller, view, model, store, and utility files with app.js.

app.js − The main file from where the flow of program will start. It should be included in main HTML file using <script> tag. App calls the controller of application for rest of the functionality.

Controller.js − It is the controller file of Sencha Touch MVC architecture. This contains all the control of the application, the events listeners, and most of the functionality of the code. It performs the following tasks: routing, intermediate between view and model, and executes events.

View.js − It contains the interface part of the application, which shows up to the user. Sencha Touch uses various UI rich views, which can be extended and customized according to the requirement.

Store.js − It contains the locally cached data, which is to be rendered on view with the help of model objects. Store fetches the data using proxies, which has the path defined for services to fetch the backend data.

Model.js − It contains the objects which binds the store data to view. It is the representation of the real-world object, which basically deals with the database.

Utils.js − It is not included in MVC architecture but it is a best practice to use this so as to make the code clean, less complex, and more readable. We can write methods in this file and call them in controller or view renderer wherever required. It is helpful for code reusability purpose as well.

Sencha Touch - MVC

MVC stands for Model View Controller. It is an architectural pattern which separates the application into logical components making it more manageable.

The following diagram shows how MVC architecture works −

MVC

Controller − Controller controls whole application it notify view if model is changed and performs actions based on user inputs.

View − It contains the interface part of the application which is visual to user. It notify controller to change model on user input.

Model − It contains the objects which binds the store data to view. It is representation of the real world object which basically deals with database. It also notify controller for any change in view.

Sencha Touch - First Program

In this chapter, we will list down the steps to write the first Hello World program in Ext JS.

Step 1

Create an index.htm page in an editor of our choice. Include the required library files in the head section of html page as follows.

index.htm

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js">
      </script>
      <script type = "text/javascript">
         Ext.application( {
            name: 'Sencha', launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true, items: [{
                     title: 'Home', iconCls: 'home', html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
   
   <body>
   </body>
</html>

Explanation

  • Ext.application() method is the starting point of Sencha Touch application. It creates a global variable called 'Sencha' declared with the name property - all the Application's classes such as its Models, Views and Controllers will reside under this single namespace, which reduces the chances of colliding global variables and file names.

  • launch() method is called once the page is ready and all the JavaScript files are loaded.

  • Ext.create() method is used to create an object in Sencha Touch. Here, we are creating an object of simple panel class Ext.tab.Panel.

  • Ext.tab.Panel is the predefined class in Sencha Touch for creating a panel.

  • Every Sencha Touch class has different properties to perform some basic functionalities.

Ext.Panel class has various properties such as −

  • fullscreen property is to make use of a complete screen, hence the panel will take fullscreen space.

  • items property is the container for various items.

  • iconCls is the class used for displaying different icons.

  • title property is to provide the title to the panel.

  • html property is the html content to be shown in the panel.

Step 2

Open the index.htm file in a standard browser and you will get the following output.

Sencha Touch - Builds

Today's demand for a web application is to develop a fast application with less development efforts. Sencha Touch helps in doing so with ease as it provide a number of build libraries to choose from, based on the development or production code along with the facility to create a custom build.

Sencha Touch build libraries loads the classes dynamically. Dynamic loading stands for the classes that gets loaded when required and only those classes will be included which are required in the application. This makes the application run faster as the number of files to be loaded reduces, simultaneously decreasing the time to load.

Sencha Touch 2.x provides the following five build libraries.

Sr.No. Builds & Usage
1

sencha-touchdebug.js

This build is used while developing the application locally. It is a nonminified version with all the comments and debug logs for easy debugging while development.

2

senchatouch.js

This file is used for production purpose. It is the minified version when we have a custom build.

3

sencha-touchall.js

This file is used for production purpose. It is the minified version when we do not have a custom build.

4

sencha-touchall-debug.js

This file is used for debugging in production. It is not minified and has all the comments and debug logs.

5

sencha-touchall-compat.js

This build is used to migrate the version 1.x to version 2.x. It gives a warning wherever version 1.x code is not compatible and needs code modification.

With the above mentioned builds, Sencha Touch provides a facility to create custom builds.

Advantages of Having a Custom Build

Custom build does not load all the touch files. It loads only those files, which we are using in the application, which makes the application faster and easily maintainable.

Sencha CMD is used to create a custom build. To create a custom build in Sencha CMD, go to the directory where the app file resides and type one of the following commands to create a build.

Sr.No. Command & Usage
1

sencha app build native

Builds the app and prepares a file called packager.temp.json that you can use to package an application--the packager.temp.json is the same as packager.json, but contains additional paths.

2

sencha app build -run native

Builds and automatically packages the application, and launches the appropriate simulator.

3

sencha app build package

Builds the app with packaging support, but does not configure a packager JSON file. This is useful for projects that manually maintain multiple packager.json files.

Once the build is successful, it will generate all-classes.js file which we need to include in our index.html to make it production ready.

Following code shows the changes to be done for production ready code.

Index.html before building application

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-debug.js"></script>
      <script type = "text/javascript" src = "app.js"> </script>
   </head>
   <body>
   </body>
</html>

Index.html after building the application

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch.js"></script>
      <script type = "text/javascript" src = "app.js"> </script>
      <script type = "text/javascript" src = "app-classes.js"> </script>
   </head>
   <body>
   </body>
</html>

Sencha Touch - Migration

Sencha Touch comes with various rectifications from the earlier version.

Sencha Touch 2 comes with the backward compatibility build, which makes the migration process easier from version 1.x to 2.x.

This build just makes the work easier by providing a warning and the logs whenever any migration issue occurs or code change is required, so the user will get to know where the changes are must, to make sure the application works with the latest version.

Sencha Touch 2.x migration requires the following code changes.

Class System

Code in Sencha Touch 1.x

MyApp.view.StudentPanel = Ext.extend(Ext.Panel, {
   scroll: 'vertical',
   html: 'Student Panel'
   initComponent: function() {
      Ext.getCmp('StudentIdDiv').update('This is a Student panel');
   }
});

Code in Sencha Touch 2.x

Ext.define('MyApp.view.StudentPanel', {
   extend: 'Ext.Panel',

   config: {
      scroll: 'vertical',
      html: 'Student Panel'
   },

   initialize: function() {
      Ext.getCmp('StudentIdDiv').setHtml('This is a Student panel')
   }
});

By looking at both the versions, you can see the way to create class is changes which is now inspired by ExtJs such as −

  • Ext.extend is changed to Ext.define.

  • All the configuration parameters related to the class are now defined under config parameter.

  • The initComponent is changed to initialize() method.

  • In Sencha Touch 2.x, we can have setHtml() and getHtml() functions to update html or to get the value.

MVC Architecture

Sencha Touch 1.x code was modular and based on MVC architecture. Sencha Touch 2.x follows a different syntax for writing model, view, and controller. Let’s see the difference of model, view, and controller files in different versions.

Model

Code in Sencha Touch 1.x

Ext.regModel('MyApp.model.StudentModel', {
   fields: [
      {name: 'name',  type: 'string'},
      {name: 'age',   type: 'int'}
   ]
});

Code in Sencha Touch 2.x

Ext.define('MyApp.model.StudentModel', {
   extend: 'Ext.data.Model', config: {
      fields: [
         {name: 'name',  type: 'string'},
         {name: 'age',   type: 'int'}
      ]
   }
});

Ext.regModel is changed to Ext.define which extends Ext.data.Model.

All the fields come under config section now in 2.x version.

View

Code in Sencha Touch 1.x

Ext.Panel("studentView", {
   items: [{}]
});

Code in Sencha Touch 2.x

Ext.define('MyApp.view.StudentView', {
   extend: 'Ext.tab.Panel',
   items: [{}]
});  

View is almost the same, the only change being the view name follows the 2.x version namespacing such as Myapp.view.StudentView and code is writing in Ext.define method as like model.

Controller

Code in Sencha Touch 1.x

Ext.regController("studentController", {
   someMethod: function() {
      alert('Method is called');
   }
});

Code in Sencha Touch 2.x

Ext.define('MyApp.controller.studentController', {
   extend: 'Ext.app.Controller', someMethod: function() {
      alert('Method is called');
   }
});

Same as model in controller. Also the Ext.regController is changed into Ext.define, which extends Ext.app.Controller.

Application

Code in Sencha Touch 1.x

Ext.application({
   name: 'MyApp',
   launch: function() {
      Ext.create('MyApp.view.StudentView');
   }
});

Code in Sencha Touch 2.x

Ext.application({
   name: 'MyApp',
   models: ['studentModel'],
   controllers: ['studentController'],
   views: ['studentView'],
   stores: ['studentStore'],

   launch: function() {
      Ext.create('MyApp.view.Main');
   }
});

The major difference between version 1.x and version 2.x is, in 2.x we declare all model, views, controllers, and stores in the application itself.

Sencha Touch - Core Concept

Sencha Touch has various core concepts such as class system, ajax, controllers, etc.

Following table lists the link for core concepts of Sencha Touch.

Sr.No. Concept & Description Link
1 Class System
2 Components
3 Controllers
4 BlackBerry support
5 Use of Ajax

Sencha Touch - Data Package

Data package in Sencha Touch is responsible for carrying out any kind of data manipulation either storing or loading the data.

Data packages are related to model, store, and proxies.

Sr.No. Concept & Description Link
1

Model

It is the collection of data and fields with which we display all the values on UI. Description

2

Store

It is a collection of model instances which basically stores the data locally. In store we write all the events and rest calls to get data. Description

3

Proxy

It is basically responsible for loading data in store. Mostly we use ajax proxy to load store data. Description

Sencha Touch - Theme

Sencha Touch provides a number of themes to be used in your applications. You can add different themes in place of classic theme and see the difference in the output based on the device we are using for the application. This is done simply by replacing the theme CSS file as explained in the following example.

Desktop Theme

Consider your very first Hello World application. The following CSS from the application is used for desktop theme.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css

To see the effect, try the following program −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type="text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true,
                  items: [{
                     title: 'Home',
                     iconCls: 'home',
                     html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
</html>

This will produce following result −

Windows Theme

Consider your very first Hello World application. Remove the following CSS from the application −

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css

Add the following CSS to use Windows theme.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/wp.css

To see the effect, try the following program −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/wp.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true,
                  items: [{
                     title: 'Home',
                     iconCls: 'home',
                     html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
</html>

This will produce following result −

IOS Theme

Consider your very first Hello World application. Remove the following CSS from the application.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css

Add the following CSS to use Windows theme

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/cupertino.css

To see the effect, try the following program −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/cupertino.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true,
                  items: [{
                     title: 'Home',
                     iconCls: 'home',
                     html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
</html>

This will produce following result −

IOS Classic Theme

Consider your very first Hello World application. Remove the following CSS from the application −

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css

Add the following CSS to use Windows theme −

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/cupertino-classic.css

To see the effect, try the following program −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/cupertino-classic.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true,
                  items: [{
                     title: 'Home',
                     iconCls: 'home',
                     html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
</html>

This will produce following result −

Android Theme

Consider your very first Hello World application. Remove the following CSS from the application.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css

Add the following CSS to use Windows theme.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/mountainview.css

To see the effect, try the following program −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/mountainview.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true,
                  items: [{
                     title: 'Home',
                     iconCls: 'home',
                     html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
</html>

This will produce following result −

BlackBerry Theme

Consider your very first Hello World application. Remove the following CSS from the application.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css

Add the following CSS to use Windows theme.

https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/bb10.css

To see the effect, try the following program −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/bb10.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               Ext.create("Ext.tab.Panel", {
                  fullscreen: true,
                  items: [{
                     title: 'Home',
                     iconCls: 'home',
                     html: 'Welcome to sencha touch'
                  }]
               });
            }
         });
      </script>
   </head>
</html>

This will produce following result −

Sencha Touch - Device Profile

In today's world of technologies, we have multiple devices such as mobile, tablet, desktop, and laptop with different screen sizes. Hence, there is a need to develop applications, which are accessible from all the devices with good look and feel. However, to develop different code for different devices is very time consuming and costly.

Sencha Touch helps us in this regard, by offering a device profile feature. Based on the active profile, the different dependencies will be run and applicable.

We can declare device profile while writing an application code. We can have multiple devices as −

Ext.application({
   name: 'MyApp',
   profiles: ['Phone', 'Tablet']
});

Once it is done, the profiles will be loaded as −

  • MyApp.profiles.Phone.js
  • MyApp.profiles.Tablet.js

Writing a simple phone profile

Ext.define('Mail.profile.Phone', {
   extend: 'Ext.app.Profile',

   config: {
      name: 'Phone',
      views: ['phoneView']
   },

   isActive: function() {
      return Ext.os.is('Phone');
   }
});

Writing a simple tablet profile

Ext.define('Mail.profile.Tablet', {
   extend: 'Ext.app.Profile',

   config: {
      name: 'Tablet',
      views: ['tableView']
   },

   isActive: function() {
      return Ext.os.is('Tablet');
   }
});

As we can see in profile, we have isActive function which determines if the particular device is active. If the device is active, the corresponding dependencies will be loaded and instantiated.

As mentioned in the above example, if we are using phone device then phone profile's isActive function will return true and the dependencies related to the phone device will be loaded; here phoneView will be loaded. If the device is a tablet then phone profile's isActive function will return false and tablet profile's isActive function will return true and dependency tabletView will be loaded.

Launch Process

One more point to be noticed here is when we have profiles in the application, then the loading and instantiation of application code will be in the following order −

  • Controllers are instantiated first and each controller's init function will be loaded.
  • Profile's launch function will be called.
  • Application's launch function will be called.

Both profile and application's launch functions are optional, so if we do not define any one of them they will not get called.

Take a look at the following code to check where and how the different launch and init functions can be defined.

Controller's init function

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller',
   
   init : function (){
      Ext.Msg.alert('Controller's init method');
   },
   
   config: {
      refs: {
         tab: '#divId
     }
   }
});

Profile's launch function

Ext.define('Mail.profile.Tablet', {
   extend: 'Ext.app.Profile',

   config: {
      name: 'Tablet', views: ['tableView']
   },

   isActive: function() {
      return Ext.os.is('Tablet');
   }
   launch : function() {
      Ext.Msg.alert('profile's launch function');
   }
});

Application's launch function

Ext.application({
   name: 'Sencha', launch: function() {
      Ext.Msg.alert(Application's launch function);
   }
});

Sencha Touch - Dependencies

There are certain ways defined in Sencha Touch to declare dependencies, one within the application and the other inside the classes.

Let’s take a look at the different ways to define dependencies.

Application Level Dependencies

Here, we declare all the dependencies when we create Ext.application.

Ext.application({
   name: 'MyApp',
   views: ['StudentsView'],
   models: ['StudentsModel'],
   controllers: ['StudentsController'],
   stores: ['StudentsStore'],
   profiles: ['Phone', 'Tablet']
});

Now, when the application gets loaded, all the dependencies will be loaded at the same time. The path of the other files will be −

  • MyApp.views.StudentsView
  • MyApp.models.StudentsModel
  • MyApp.stores.StudentsStore etc.

The above way of declaration not only loads the file, it also decides which profile it should keep as active. After loading the controller, it makes sure to instantiate it. Once the stores are loaded, it instantiates them and provides one id if not already given.

Profile-specific Dependencies

When we are using profiles in an application, there may be possibilities that few functionalities are only required for some specific profile.

Profile specific dependencies are declared in the profiles itself instead of the application level declaration.

Ext.define('MyApp.profile.Tablet', {
   extend: 'Ext.app.Profile', config: {
      views: ['StudentView'], controllers: ['StudentController'], models: ['StudentModel']
   }
});

Dependencies get loaded irrespective of the profile being active or not. However, based on the active profile, further processing such as instantiating controller and stores happens.

Nested Dependencies

When we have larger application we have multiple controllers, models, views, and stores.

It is always good to keep modularity in larger applications. For that, we can define subfolders and while declaring dependencies we can use subfolder name to declare.

Ext.application({
   name: 'MyApp',
   controllers: ['Controller', 'nested.NewController'],
   views: ['class.Cview', 'SView']
});

In the above case, following files will be loaded −

  • MyApp.controllers.Controller
  • MyApp.controllers.nested.NewController
  • MyApp.Views.Sview
  • MyApp.Views.class.Cview

External Dependencies

We can specify the dependencies outside the application by giving fully qualified names of the classes as −

Ext.Loader.setPath({
   'Class': 'Class'
});

Ext.application({
   views: ['Class.view.LoginForm', 'Welcome'],
   controllers: ['Class.controller.Sessions', 'Main'],
   models: ['Class.model.User']
});

In the above case, following files will be loaded −

  • Class/view/LoginForm.js
  • Class/controller/Sessions.js
  • Class/model/User.js
  • app/view/Welcome.js
  • app/controller/Main.js

Sencha Touch - Environment Detection

It helps you in identifying which operating system you are using, which browser you are working on, and what are the features available for your environment.

Sencha Touch provides different functions to get information specific to the environment. All the methods mentioned below can be checked in, if the condition is if(Ext.os.is.Windows){} and is based on the condition tasks can be performed.

All the following methods return Boolean value.

Operating System

Ext.os is a class that gives you different methods to know which operating system we are working on.

Sr.No Method & Description
1

Ext.os.is.webOS

This function will return true if you are using webos operating system else it returns false.

2

Ext.os.is.RIMTable

This function will return true if you are using RIMTable operating system else it returns false.

3

Ext.os.is.Linux

This function will return true if you are using Linux operating system else it returns false.

4

Ext.os.is.Windows

This function will return true if you are using windows operating system else it returns false.

5

Ext.os.is.MacOs

This function will return true if you are using Mac operating system else it returns false.

6

Ext.os.is.BlackBerry

This function will return true if you are using BlackBerry operating system else it returns false.

7

Ext.os.is.iOS

This function will return true if you are using IOS operating system else it returns false.

8

Ext.os.is.Android

This function will return true if you are using Android operating system else it returns false.

Device Detection

Sr.No Method & Description
1

Ext.os.is.iPad

This function will return true if you are using iPad else it returns false.

2

Ext.os.is.iPhone

This function will return true if you are using iPhone else it returns false.

3

Ext.os.is.iPod

This function will return true if you are using iPod else it returns false.

Version of Operating System

Sr.No Method & Description
1

Ext.os.name

It returns the name of the operating system.

2

Ext.os.version.version

It gives the version of operating system we are using.

Browser Detection

Sr.No Method & Description
1

Ext.browser.is.IE

This function returns true if we are using Internet explorer browser else it returns false.

2

Ext.browser.is.FF

This function returns true if we are using FireFox browser else it returns false.

3

Ext.browser.is.Chrome

This function returns true if we are using Chrome browser else it returns false.

4

Ext.browser.is.Opera

This function returns true if we are using Opera browser else it returns false.
5

Ext.browser.is.Safari

This function returns true if we are using Safari browser else it returns false.

This function Ext.browser provides various other functions −

Sr.No Method & Description
1

Ext.browser.userAgent

It returns the current userAgent.

2

Ext.browser.isSecure

It returns true if the current page is using SSL.

3

Ext.browser.isStrict

It returns true if the browser is in strict mode.

4

Ext.browser.engineName

It returns the browser engine name (WebKit, Gecko, Presto, Trident and Other).

5

Ext.browser.engineVersion

It returns the version of the browser engine.

Features

Ext.feature.has is to check if the browser has following feature or not.

Sr.No Method & Description
1

Ext.feature.has.Audio

This method returns true if browser supports audio tag feature of html5.

2

Ext.feature.has.Canvas

This method returns true if browser supports canvas tag feature of html5.

3

Ext.feature.has.classList

This method returns true if browser supports classlist feature of html5 which is used to add, remove and toggle css classes for the html element.

4

Ext.feature.has.Css3dTransforms

This method returns true if browser supports Css 3d Transform feature of css3.

5

Ext.feature.has.CssAnimations

This method returns true if browser supports animations of css3.

6

Ext.feature.has.CssTransforms

This method returns true if browser supports Css transform feature of css3.

7

Ext.feature.has.CssTransitions

This method returns true if browser supports transition feature of css3.

8

Ext.feature.has.DeviceMotion

This method returns true if browser supports the device motion feature.

9

Ext.feature.has.Geolocation

This method returns true if browser supports the Geolocation feature of html5.

10

Ext.feature.has.History

This method returns true if browser Supports history feature of html.

11

Ext.feature.has.Orientation

This method returns true if browser can detect which the device orientation.

12

Ext.feature.has.OrientationChange

This method returns true if browser can detect change in Orientation of the device.

13

Ext.feature.has.Range

Range is a type of html input tag for range slider element so if browser supports slider this function returns true.

14

Ext.feature.has.SqlDatabase

Web sql database is a web page api for storing data n database on which we can perform query operations. This method returns true if browser supports web Sql Database.

15

Ext.feature.has.Svg

Svg stands for Scalable Vector Graphics this method returns true if browser supports html 5's svg feature.

16

Ext.feature.has.Touch

This method returns true if browser has Touch feature.

17

Ext.feature.has.Video

This method returns true if browser supports html 5 video tags.

18

Ext.feature.has.Vml

Vml stands for vector markup language which is an xml based markup language. So this method returns true if browser has supports vml.

19

Ext.feature.has.WebSockets

Web socket is basically a communication protocol for computers which supports two communication between clients and server. This method returns true if browser Supports WebSockets else it returns false.

Sencha Touch - Events

Events are something which get fired when something happens to the class. For example, when a button is getting clicked or before/after an element is rendered.

Methods of Writing Events

Following are the methods of writing events.

  • Built-in events using listeners.
  • Attaching events later
  • Custom events

Built-in Events Using Listeners

Sencha Touch provides listener property for writing events and custom events in Sencha Touch files.

Writing listener in Sencha Touch

We will add the listener in the previous program itself by adding listen property to the panel, shown as follows −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha', launch: function() {
               Ext.create('Ext.Panel', {
                  html: 'My Panel', fullscreen: true, listeners: {
                     painted: function() {
                        Ext.Msg.alert('I was painted to the screen');
                     }
                  }
               });
            }
         });
      </script> 
   </head>
</html>

This will produce following result −

This way we can also write multiple events in listeners property.

Multiple events in the same listener

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">   
         Ext.application({
            name: 'Sencha',
            launch: function() {
               var myButton = Ext.Viewport.add({
                  xtype: 'button',
                  centered: true,
                  text: 'Click me'
               });

               myButton.on({
                  tap: function() {
                     var randomWidth = 100 + Math.round(Math.random() * 200);
                     this.setWidth(randomWidth);
                  },
                  widthchange: function(button, newWidth, oldWidth) {
                     alert('My width changed from ' + oldWidth + ' to ' + newWidth);
                  }
               });
            }
         });       
      </script> 
   </head>
</html>

It will produce the following result −

Attaching event later

In the previous method of writing events, we have written events in listeners at the time of creating elements.

The other way to attach events is as follows −

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               var myButton = Ext.Viewport.add({
                  xtype: 'button',
                  centered: true,
                  text: 'Click me'
               });
               
               myButton.on('tap', function() {
                  alert("Event listener attached by .on");
               });
            }
         });
      </script> 
   </head>
</html>

It will produce the following result −

Custom events

We can write custom events in Sencha Touch and fire the events with fireEvent method. Following example explains how to write custom events.

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.application({
            name: 'Sencha',
            launch: function() {
               var myButton = Ext.Viewport.add({
                  xtype: 'button',
                  centered: true,
                  text: "Just wait 5 seconds",

                  listeners: {
                     myEvent: function(button, points) {
                        alert('myEvent was fired! You score ' + points + ' points');
                     }
                  }
               });

               Ext.defer(function() {
                  var number = Math.ceil(Math.random() * 100);
                  myButton.fireEvent('myEvent', myButton, number);
               }, 5000);
            }
         });
      </script> 
   </head>
</html>

Once the page is loaded and the document is ready, the UI page with button will appear and as we are firing an event after 5 seconds, once the document is ready the alert box will appear after 5 seconds.

Here we have written the custom event 'myEvent' and we are firing events as button.fireEvent(eventName);

Sencha Touch - Layout

Layout is the way the elements are arranged in a container. That could be horizontal, vertical, or any other. Sencha Touch has different layouts defined in its library though we can always write custom layouts as well.

Sr.No. Layout & Description
1 hBox

This layout allows the element to be distributed in a horizontal manner.

2 vBox

This layout allows the element to be distributed in a vertical manner. This is one of the commonly used layout.

3 Fit

In this layout, the container is filled with a single panel and when there is no specific requirement related to the layout, then this layout is used.

4 Card(TabPanel)

This layout arranges different components in tab fashion. Tabs will be displayed on top of the container. Every time only one tab is visible and each tab is considered as a different component.

Sencha Touch - History Support

Sencha Touch comes with full history support and deep linking facilities.

It has the simplest back button functionality, which helps the user navigate between the screens, without even refreshing the page or application.

It also provides routes functionality, which helps the user navigate to any URL. Based on the URL provided in the browser window, it calls specific functions to perform a specific task.

Look at the following example for back button functionality.

This example shows the nested list which is nothing but a list inside a list, so when you click any of the list items, it opens another list and a back button appears on top of the screen.

For complete code base, you can check Nested List under view component section.

Routing

Simplest example of routes

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller',

   config: {
      routes: {
         login: 'showLogin',
		 'user/:id': 'userId'
      }
   },

   showLogin: function() {
      Ext.Msg.alert('This is the login page');
   },
   userId: function(id) {
      Ext.Msg.alert('This is the login page specific to the used Id provided');
   }
});

In the above example if browser URL is https://myApp.com/#login then the function showLogin will be called.

We can provide parameters in the URL and based on the specific parameter the function can get called. For example If the URL is https://myApp.com/#user/3 then the another function userId will be called and the specific ID can be used inside the functions.

Advance routing

Sometime we have advance parameters which includes comma, blank space and special characters etc. for this if we use the above way of writing routes then it will not work. To solve this problem Sencha touch provides conditional routing where we can specify condition of what type of data the parameter should accept.

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller', config: {
      routes: {
         login/:id: {
            action: showLogin, conditions: {':id: "[0-9a-zA-Z\.]+" }      
         }
      },

      showLogin: function() {
         Ext.Msg.alert('This is the login page with specific id which matches criteria');
      }     
   }
});

So as in the above example we have given regex in the condition which clearly states what type of data should be allowed as URL parameter.

Sharing same URL across different device profiles

As Sencha touch provides device profile so the same application code can be used across multiple devices there may be possibilities that different profiles may have different functionality for the same URL.

To resolve this issue Sencha touch gives us freedom to write routing in the main controller and the called function to be written in the all the profile with their profile specific ones.

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller', config: {
      routes: {
         login: 'showLogin'
      }
   },
});
// For phone profile
Ext.define('MyApp.controller.phone.Main, {
   extend: 'MyApp.controller.Main, showLogin: function() {
      Ext.Msg.alert('This is the login page for mobile phone profile');
   }
});
// For tablet profile
Ext.define('MyApp.controller.tablet.Main, {
   extend: 'MyApp.controller.Main,showLogin: function() {
      Ext.Msg.alert('This is the login page for tablet profile');
   }
});

As example shows we have one main controller which has showLogin function and we have two different profiles(Phone/ Tablet). Both the profile has showLogin function with different code specific to the profile.

This way we can share same URL across multiple profile devices with their specific functionalities.

Sencha Touch - Upload & Download

Sencha Touch provides XHR2 configuration to work with Ajax and Ajax2 development.

XHR2 is xmlHttpRequest level 2, which used to request data from the server. For any web application, data resides at the server and once the page is loaded, the data should be accessed from the server with the help of Ajax requests.

XHR2 in Sencha Touch provides the progress bar feature, which shows the user the amount of data transferred for a particular request. XHR2 is newly added so we need to check if the browser supports it or not.

Following is the function to check whether the browser supports XHR2 −

if (Ext.feature.has.XHR2) {
   // Here we can write functionality to work if browser supports XHR2 
}  

We can even check if the progressive upload with XHR2 is supported by the browser or not.

if (Ext.feature.has.XHRUploadProgress) {
   // Here we can write functionality to work if browser supports progressive uploads
}

Various new XHR2 features are included in Sencha Touch.

Sr.No Features & Description
1

XHR2: true

This is used to enable and disable XHR2 functionality in the application.

2

Ext.field.File

New file field is added to give more cality about the type of field.

3

Ext.field.FileInput

This to provide FileInput.

4

Ext.progressIndicator

This is to provide exact percentage of data transferred in terms of progress bar.

5

xtype: fileinput

To create instance of fileInput class.

6

xtype: filefield

To create instance of file class.

7

responseType : value

This parameter allows various types of responses as text, document, blob etc.

Following are the examples to send simple ajax request with and without parameter and uploading files using ajax.

Simple Ajax request without parameters - Success

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.setup({
            requires: [ 'Ext.Panel', 'Ext.Button', 'Ext.form.Panel'], onReady: function() {
               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/index.htm',
                  method: 'POST',
                  xhr2: true,
                  success: function(response) {
                     Ext.Msg.alert('Ajax call successful');
                  },
                  failure: function(response) {
                     Ext.Msg.alert('Ajax call failed');
                  }
               };
               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"button",
                        text: "Ajax",
                        ui: 'confirm',
                        handler: function(){
                           Ext.Ajax.request(request);
                        }
                     }
                  ]
               });
            }
         });
      </script>
   </head>
   <body>
   </body>
</html>

It will produce the following result −

The above example shows the success ajax call as the URL mentioned is correct. In this example, we are not passing any parameter, it’s just a simple ajax request which hits the URL mentioned.

If you are using the chrome browser in the developer tool, navigate to the network section, you can see the request which is being sent and the response which we get.

Simple Ajax request without parameters - Failure

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.Button',
               'Ext.form.Panel'
            ],
            onReady: function() {
               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/indexx.htm',
                  method: 'POST',
                  xhr2: true,
                  success: function(response) {
                     Ext.Msg.alert('Ajax call successful');
                  },
                  failure: function(response) {
                     Ext.Msg.alert('Ajax call failed');
                  }
               };
               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"button",
                        text: "Ajax",
                        ui: 'confirm',
                        handler: function(){
                           Ext.Ajax.request(request);
                        }
                     }
                  ]
               });
            }
         });
      </script>
   </head>
   <body>
   </body>
</html>

It will produce the following result −

In the above example, just to show how ajax failure works we have mentioned the wrong URL. Compare this and the previous example, you will find the difference.

Sending parameters in Ajax request

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.Button',
               'Ext.form.Panel'
            ],

            onReady: function() {
               var formData = new FormData();
               formData.append("firstName", "Hi");
               formData.append("lastName", "Reader");

               // Request will be sent as part of the payload instead of standard post data
               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/sencha_json.php',
                  method: 'POST',
                  xhr2: true,
                  data: formData,
                  success: function(response) {
                     var out = Ext.getCmp("output");
                     response = Ext.JSON.decode(response.responseText, true);
                     Ext.Msg.alert(response.message);
                  },
                  failure: function(response) {
                     var out = Ext.getCmp("output");
                     Ext.Msg.alert('Ajax failed!');
                  }
               };

               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"button",
                        text: "Ajax",
                        ui: 'confirm',
                        handler: function(){
                           Ext.Ajax.request(request);
                        }
                     }
                  ]
               });
            }
         });      
      </script>
   </head>
   <body>
   </body>
</html>

It will produce the following result −

In this example, we are passing parameters with the ajax using data property of ajax call.

Uploading files using Ajax

Live Demo
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel = "stylesheet" />
      <script type = "text/javascript" src = "https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type = "text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.MessageBox',
               'Ext.Button',
               'Ext.ProgressIndicator',
               'Ext.form.Panel',
               'Ext.field.FileInput'
            ],

            onReady: function() {
               var progressIndicator = Ext.create("Ext.ProgressIndicator", {
                  loadingText: "Uploading: {percent}%"
               });

               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/sencha_json.php',
                  method: 'POST',
                  xhr2: true,
                  progress:progressIndicator,
                  success: function(response) {
                     Ext.Msg.alert('File uploaded successfully.');
                  },
                  failure: function(response) {
                     Ext.Msg.alert('File upload failed.');
                  }
               };

               Ext.Viewport.add(progressIndicator);
               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"fileinput",
                        accept:"image/jpeg"
                     },
                     {
                        xtype:"button",
                        text: "Upload",
                        ui: 'confirm',
                        handler: function(){
                           var input = Ext.Viewport.down("fileinput").input;
                           var files = input.dom.files;
                           if (files.length) {
                              request.binaryData = files[0];
                              Ext.Ajax.request(request);
                           }else {
                              Ext.Msg.alert("Please Select a JPG");
                           }
                        }
                     }
                  ]
               });
            }
         });
      </script>
   </head>
   <body>
   </body>
</html>

It will produce the following result −

This example shows how to upload data using ajax call. In this example, we are using the progress bar indicator to show the progress while uploading the file.

Sencha Touch - View Components

Sencha Touch provides various UI components, which can be customized according to requirements.

Sr.N0. Component & Description
1 Carousel

This UI component is used to display Carousel.

2 List

This UI component is used to display lists.

3 Nested List

This UI component is used to display nested list.

4 Form

This UI component is used to display Forms.

5 Chart

This UI component is used to display different types of charts.

6 Floating Component

This UI component is used to display floating component.

7 Tab Panel

This UI component is used to display Tab panel view.

8 Navigation View

This UI component is used to display navigation view.

9 Action Menu

This UI component is used to display action menu bar.

10 Data View

This UI component is used to display data view.

11 Map

This UI component is used to display google map.

Sencha Touch - Packaging

Sencha Touch comes with native packaging features.

Following are the links for native packaging concepts of Sencha Touch.

Sr.No. Concept & Description Link
1 Native iOS provisioning
2 Native APIs

Sencha Touch - Best Practice

Basic JavaScript best practice

It is a good practice to keep all JavaScript-related code in a separate js (external JS) file, instead of writing it in the <script> tag under the head section or inline JavaScript in the document body.

Always perform a null check before the element is being used in further logic.

Always follow the naming convention, as it makes the code easy to understand by any other programmer.

To make the code easily understandable, it is always preferred to write comments for JS methods with clear logic behind what a function does.

Best practice specific to Sencha Touch

Use Sencha Touch recommended folder structure, which will be helpful during JS compression or minification.

It is highly recommended to use the listener (onclick/onblur, etc.) in the controller instead of writing it in the html page itself.

Do not create the store instance, when the store is being called from the view.

When we create an instance of a store, we should always destroy it, as it impacts the performance.

While using Sencha Touch, do not specify any other simple JavaScript file. Use all the functions from Ext classes (mentioned in controller or utils).

When the model mapping and the name are same, then do not specify mapping. Only name will solve the purpose.

Do not use unnecessary properties in view. Use only the property which is required and it value which is different from the default value.

Advertisements