Book Image

Instant Sencha Touch

By : Hiren Dave
Book Image

Instant Sencha Touch

By: Hiren Dave

Overview of this book

Sencha Touch, a high-performance HTML5 mobile application framework, is the cornerstone of the Sencha HTML5 platform. Built for enabling world-class user experiences, Sencha Touch is the only framework that enables developers to build fast and impressive apps that work on iOS, Android, BlackBerry, Kindle Fire, and more. Instant Sencha Touch is a practical hands on guide that provides you with all you need to explore the Sencha Touch framework and start building high performance, cross platform mobile applications with rich user interfaces. It also covers native deployment of Sencha Touch applications on various platforms. Instant Sencha Touch is a step-by-step guide that will explain you everything from downloading Sencha Touch SDK to setting up the development environment, and building applications. You will start with a quick overview of the Sencha Touch and work your way through understanding the class structure, and basic components and layouts of the Sencha Touch. You will also cover interesting features like animations, adaptive layout, data packages, local storage support, and so on. You will also see how to build your own theme and styles and deploy Sencha Touch app as native apps. You will also learn about MVC architecture for building Sencha Touch applications. Finally you will take a look at the Phonegap (Cordova) build and Cordova SDK to deploy Sencha Touch application as native application.
Table of Contents (6 chapters)

Quick start – building a Hello World application


This section will give more insight on Sencha Touch by introducing some of the controls and components that are widely used in real-time applications.

The Hello World application

In the previous sections, we saw how to set up environments for development of Sencha Touch. Now let's start with the Hello World application.

First of all, create a new folder in your web server and name it sencha-touch-start. Create a subfolder lib inside this folder. In this folder, we will store our Sencha Touch resources. Create two more subfolders inside the lib folder and name them js and css respectively. Copy the sencha-touch-all.js file from the SDK, which we had downloaded, to the lib/js folder. Copy the sencha-touch.css file from SDK to the lib/css folder. Now, create a new file in the sencha-touch-start folder, name it index.html, and add the following code snippet to it:

<!DOCTYPE html> 
<html> 
    <head> 
        <meta charset="utf-8"> 
        <title>Hello World</title> 
 
        <script src="lib/js/sencha-touch-all.js" type="text/javascript"></script> 
        <link href="lib/css/sencha-touch.css" rel="stylesheet" type="text/css" /> 
 
    </head> 
    <body></body> 
</html>

Now create a new file in the sencha-touch-start folder, name it app.js, and add the following code snippet to it:

Ext.application({
  name: 'Hello World',
    launch: function () {
        var panel = Ext.create('Ext.Panel', {
          fullscreen: true,
            html: 'Welcome to Sencha Touch'
        });
        Ext.Viewport.add(panel);
    }
});

Add a link to the app.js file in the index.html page; we created the following link to sencha-touch-all.js and sencha-touch.css:

<script src="app.js" type="text/javascript"></script>

Here in the code, Ext.application({..}) creates an instance of the Ext.Application class and initializes our application. The name property defines the name of our application. The launch property defines what an application should do when it starts. This property should always be set to a function inside which we will add our code to initialize the application. Here in this function, we are creating a panel with Ext.create and adding it to Ext.Viewport. Ext.Viewport is automatically created and initialized by the Sencha Touch framework. This is like a base container that holds other components of the application.

At this point, your application folder structure should look like this:

Now run the application in the browser and you should see the following screen:

Note

If your application does not work, please check your web server. It should be turned on, and the steps mentioned earlier should be repeated.

Now we will go through some of the most important features and configurations of Sencha Touch. These are required to build real-time Sencha Touch applications.

Introduction to layouts

Layouts give a developer a number of options to arrange components inside the application. Sencha Touch offers the following four basic layouts:

  • fit

  • hbox

  • vbox

  • card

hbox and vbox layouts arrange items horizontally and vertically, respectively. Let's modify our previous example by adding hbox and vbox layouts to it. Modify the code in the launch function of app.js as follows:

var panel = Ext.create('Ext.Panel', {
           fullscreen: true,
           layout: 'hbox',
           items: [{
             xtype: 'panel',
             html: 'BOX1',
             flex: 1,
             style: {
                 'background-color': 'blue'
               }
           },{
             xtype: 'panel',
             html: 'BOX2',
             flex: 1,
             style: {
                 'background-color': 'red'
               }
           },{
             xtype: 'panel',
             html: 'BOX3',
             flex: 1,
             style: {
                 'background-color': 'green'
               }
           }]
        });
        Ext.Viewport.add(panel);

In the preceding code snippet, we specified the layout for a panel by setting the layout: 'hbox' property, and added three items to the panel. Another important configuration to note here is flex. The flex configuration is unique to the hbox and vbox layouts. It controls how much space the component will take up, proportionally, in the overall layout. Here, we have specified flex : 1 to all the child containers; that means the height of the main container will be divided equally in a 1:1:1 ratio among all the three containers. For example, if the height of the main container is 150 px, the height of each child container would be 50 px. Here, the height of the main container would be dependent on the browser width. So, it will automatically adjust itself. This is how Sencha Touch adaptive layout works; we will see this in detail in later sections. If you run the preceding code example in your browser, you should see the following screen:

Also, we can change the layout to vbox by setting layout: 'vbox', and you should see the following screen:

When we specify a fit layout, a single item will automatically expand to cover the whole space of the container. If we add more than one item and specify only the fit layout, only the first item would be visible at a time. The card layout arranges items in a stack of cards and only one item will be visible at a time, but we can switch between items using the setActiveItem function. We will see this in detail in a later section.

Panel – a basic container

We have already mentioned the word "panel" in previous examples. It's a basic container component of the Sencha Touch framework. It's basically used to hold items and arrange them in a proper layout by adding the layout configuration. Besides this, it is also used as overlays. Overlays are containers that float over your application. Overlay containers can be positioned relative to some other components. Create another folder in your web server, name it panel-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>Panel Demo</title>

Modify app.js as follows:

Ext.application({
  name: 'PanelDemo',
    launch: function () {
        var panel = Ext.create('Ext.Panel', {
            fullscreen: true,
            items: [{
               xtype: 'button',
               text: 'Show Overlay',
               listeners: {
                  tap: function(button){
                     var overlay = Ext.create('Ext.Panel', {
                                                     height: 100,
                                                     width: 300,
                                                     html: 'Panel as Overlay'
                                           });
                     overlay.showBy(button);
                  }
               }
            }]
        });
        Ext.Viewport.add(panel);
    }
});

In the preceding code snippet, we have added button as the item in the panel and added listeners for the button. We are binding a tap event to a function for the button. On the tap of the button, we are creating another panel as an overlay and showing it using overlay.showBy(button).

The form panel – building rich input forms

The form panel is basically used to create forms such as login forms and registration forms. It's basically used to load and save data. You can add a number of form fields inside the form. Internally, it creates an HTML form. You can submit the form to some URL on your server, get data entered by the user on the server, and save it. Create another folder in your web server, name it form-panel-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>Form Panel Demo</title>

Modify the app.js file as follows:

Ext.application({
  name: 'FormPanelDemo',
    launch: function () {
        var form = Ext.create('Ext.form.Panel', {
           fullscreen: true,
           items: [{
              xtype: 'textfield',
              label: 'Field 1',
              name: 'field1'
           },{
              xtype: 'textfield',
              label: 'Field 2',
              name: 'field2'
           }]
        });
        Ext.Viewport.add(form);
    }
});

The preceding code will create a simple form with two text fields. We can also submit the form to an external user by specifying the GET or POST method.

form.submit({
    url: 'myurl',
    method: 'POST',
    success: function() {
        //logic after submit
    }
});

The preceding code snippet will submit the form with the POST method to the specified URL. Internally, it will create an Ajax request and send all the form fields as POST parameters with the name mentioned in the form. That's why it's mandatory to apply a name for each field in the form. Since it's an Ajax request, the success property defines a callback function to be invoked when the form's submission is successful. This is invoked automatically when a response is received from the server. In the same way, we can have the failure property in case there is some error in the response or the network is not available. We can retrieve form values by using the getValues function. It will return an object with name-value pairs. For example, refer to the following code snippet:

{
  field1: 'value1',
  field2: 'value2'
}

We can set values in the form using the setValues function and passing the same object with a key-value pair. Here, the key should match with the names of the fields in the form. For example, refer to the following code snippet:

form,setValues({
  field1: 'value1',
  field2: 'value2'
});

We can group fields inside the form panel using Ext.form.Fieldset.

{
  xtype: 'fieldset',
  title: 'Fieldset 1',
  instructions: 'Instructions for Fieldset 1',
  items: [{
    xtype: 'textfield',
    label: 'Field 1',
    name: 'field1'
  },{
    xtype: 'textfield',
    label: 'Field 2',
    name: 'field2'
  }]
}

Form fields – nifty input fields

We can add a number of fields to the form panel. Sencha Touch has a predefined set of widely used form fields. We can use those fields directly in the form panel by specifying xtype. All the input fields have a clear icon on the right-hand side so that the user can clear the values.

  • Ext.field.Checkbox xtype: checkboxfield: This field creates a new version of the HTML checkbox with a nice UI. It is used to select items from a set.

  • Ext.field.DatePicker xtype: datepickerfield: This field shows the date picker when tapped. This field is created with the UI close to the native date picker of iOS and Android.

  • Ext.field.Email xtype: emailfield: This field creates an HMTL5 e-mail field with a predefined validation for e-mails. When a user leaves the field blank or the value is not proper, it will reset the value.

  • Ext.field.Hidden xtype: hiddenfield: This field creates a native hidden field of HTML. It's not visible on the form but it can hold the string or integer value.

  • Ext.field.Number xtype: numberfield: This field creates an HMTL5 number field with a predefined validation for the number. When a user leaves the field blank or the value is not proper, it will reset the value. It will also show only the number keypad on mobile devices.

  • Ext.field.Password xtype: passwordfield: This field creates an HMTL5 password field. A user can set the characters they want to display for the password.

  • Ext.field.Radio xtype: radiofield: This field creates a new version of the HTML radio with a nice UI. It is used to select only one item from a set of items.

  • Ext.field.Search xtype: searchfield: This field creates an HMTL5 search input inside the form with a different UI.

  • Ext.field.Select xtype: selectfield: This is a simple wrapper for the HTML5 select field with a nice UI.

  • Ext.field.Slider xtype: sliderfield: This field creates a slider with a nice UI and allows a user to select values by sliding the thumb from a range of values.

  • Ext.field.Spinner xtype: spinnerfield: This field creates a wrapper over the HMTL5 number field with plus and minus buttons so that a user can change the values. A user can specify a min or max value.

  • Ext.field.Text xtype: textfield: This field creates an HTML text input with a different UI.

  • Ext.field.TextArea xtype: textareafield: This field creates an HTML text area input with a different UI.

  • Ext.field.Toggle xtype: togglefield: This field creates a special slider field with only two values and allows the user to select either of them.

  • Ext.field.Url xtype: urlfield: This field creates a wrapper over the HMTL5 URL field.

The tab panel – a tabbed set of views

The tab panel allows users to switch between various views. Each tab has its own components that will be visible when a tab is tapped. Tabs can be positioned at the top or bottom by using the tabBarPosition config. Create another folder in your web server, name it tab-panel-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>Tab Panel Demo</title>

Modify the app.js file as follows:

Ext.application({
  name: 'TabPanelDemo',
    launch: function () {
        var tabpanel =Ext.create('Ext.TabPanel', {
           fullscreen: true,
           tabBarPosition: 'bottom',
           items: [{
              title: 'Tab 1',
              html: 'Tab 1 Content'
           },
           {
              title: 'Tab 2',
              html: 'Tab 2 Content'
           }]
        });
        Ext.Viewport.add(tabpanel);
    }
});

We can also show icons for tabs or combine icons with text. Icons can be specified with the iconCls config. It accepts a CSS class name here using which we can specify the image to be displayed as the icon.

The navigation view – a smart way of navigation

The navigation view is a new introduction in Sencha Touch 2.0.0. It's much like stack-based navigation. It's basically a container with the card layout, so only one view can be visible at a time. The navigation view defines methods such as push and pop using which we can control the views. The push method is used to add a new view to the navigation view. Normally, we don't use the pop method explicitly, as it's used internally by the Back button of the toolbar. The navigation view has the default toolbar docked on top. When we push another view to the navigation view, the back button becomes visible automatically. On the tap of the back button, it will load the previous view. When the first view is displayed again, the back button is hidden again. This all happens internally. The navigation view maintains a stack of views and will load each view based on user action via the push or pop method. Create another folder in your web server, name it navigation-view-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>Navigation View Demo</title>

Modify the app.js file as follows:

Ext.application({
  name: 'NavigationViewDemo',
    launch: function () {
        var navigationview = Ext.create('Ext.NavigationView', {
           fullscreen: true,
           items: [{
              title: 'First Item',
              items: [{
                 xtype: 'button',
                 text: 'Push',
                 handler: function() {
                    navigationview.push({
                       title: 'Second Item',
                       html: 'Hello Navigation View'
                    });
                 }
              }]
           }]
        });
        Ext.Viewport.add(navigationview);
    }
});

In the preceding code snippet, we added the navigation view in the viewport with the default item, which is a button. On the tap of the button, we are pushing a new view into the navigation view using navigationview.push({..}). This will push a new item to the navigation view. When a new item is pushed, there will be a Back button in the toolbar, and on tapping it, you can go to the previous view again.

Carousels – swipe between views

Carousels allow users to swipe through multiple full-screen views. They will show only one view at a time but allow users to go back and forth with a finger swipe. There are two possible orientations, horizontal and vertical, with carousels. Create another folder in your web server, name it carousel-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>Carousel Demo</title>

Modify the app.js file as follows:

Ext.application({
  name: 'FormPanelDemo',
    launch: function () {
        var carousel = Ext.create('Ext.Carousel', {
           fullscreen: true,
           items: [
              {
                 html : 'Item 1'
              },
              {
                 html : 'Item 2'
              },
              {
                 html : 'Item 3'
              }
           ]
        });
        Ext.Viewport.add(carousel);
    }
});

The preceding code snippet will create a carousel with three items. There are indicators, which show the number of items.

Introduction to data storage

Data package is an important core part of Sencha Touch. It enables the application to persist data through the application using models and proxies. The model defines your business model that is assigned to the store, and the store is used to store a number of records for that store. First, we will define a model.

Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
          {name: field1, type: 'string', defaultValue:'empty'},
          {name: field2, type: 'int'}
        ]
    }
});

In the preceding code, we have specified a model with two fields. For each field, we can specify a name, type, and default value. There are various types available, such as int, string, number, boolean, float, and auto. If you are not sure about the type, you can assign auto.

Now define a store. Each field in the model can be set when we create an instance of the model using Ext.create. Also, you can get or set an individual field using the get and set functions of the model. For example, refer to the following code snippet:

model.get('field1');
model.set('field1','value');

Now we will define a store.

Ext.define('MyStore', {
    extend: 'Ext.data.Store', 
    config: {
        model: 'MyModel',
    }
});

In the preceding code snippet, we have defined a store and assigned a model to it. There are a number of ways to load data in the store. We can call the proxy method to store and specify a remote url value and reader.

proxy: {
  type: "ajax",
  url : "http://mydomain.com",
  reader: {
    type: "json",
    rootProperty: "root"
  }
}

In the preceding code snippet we have specified the ajax proxy and the json reader. In this case, your remote URL should return a valid JSON output with the root key as root. Keys of each object in JSON should match the model fields, only then will they be added to the store, otherwise they are ignored.

Also, we can use the store.add() method to add data to the store manually. In the store config, we can set autoLoad: true to automatically load the store, else use the store.load() method.

There are numbers or proxies available in Sencha Touch SDK that we can use, or we can create our own proxy by extending the base proxy class.

List – showing a list of data with custom styles

List is a component that allows you to show data in a list with grouping, indexing, and user-defined format. Create another folder in your web server, name it list-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>List Demo</title>

Modify the app.js file as follows:

Ext.application({
  name: 'ListDemo',
    launch: function () {
        var list = Ext.create('Ext.List', {
           fullscreen: true,
           itemTpl: '{text}',
           data: [
              { text: 'Record 1' },
              { text: 'Record 2' },
              { text: 'Record 3' },
              { text: 'Record 4' },
              { text: 'Record 5' }
           ]
        });
        Ext.Viewport.add(carousel);
    }
});

The preceding code snippet will create a simple list, which will display the records added by the data config. itemTpl is the config where we can provide a format for the list item. We can also specify the HTML code there. List also works with a store, if we want to display store records in the list. We can assign a store name using the config store: 'StoreName'. Any changes in the store will automatically refresh the list.

XTemplate – an advanced template class

The Ext.XTemplate class gives you an advanced templating mechanism with the following features:

  • Conditional processing

  • Autofeeling of an array with the for loop

  • Basic math support

It's normally used with Ext.DataView and Ext.List using the tpl config. Also, it can be used with panels and containers. The following is an example of XTemplate. Create another folder in your web server, name it template-demo, and copy all the files and folders from the sencha-touch-start folder of the previous example. Modify the title in the index.html file.

<title>Template Demo</title>

Modify the app.js file as follows:

Ext.application({
  name: 'ListDemo',
    launch: function () {
        var data = {
           student_name: 'John Mark',
           subjects: [
              { name: 'Maths', marks: '75'},
              { name: 'Science', marks: '60'},
              { name: 'English', marks: '80'}
           ]
        };
        
        var panel = Ext.create('Ext.Panel', {
           fullscreen: true,
           layout: 'vbox',
           tpl: new Ext.XTemplate(
                 '<p>Name: {student_name}',
                 '<p>Subject ------ Marks ---- Note </p>',
                 '<tpl for="subjects">',       
                 '<p>{name} ------ {marks} --- ',
                    '<tpl if="marks &lt; 70">',
                    'Below Average',
                 '</tpl></p>', 
              '</tpl></p>'
              )
        });
        Ext.Viewport.add(panel);
        panel.setData(data);
    }
});

In the preceding code snippet, we have defined a template for the panel and set up data in it. We used the for loop to display all the subjects, and the comparison operators to check for marks that are below average and display a note there.