Sencha Touch Cookbook, Second Edition

By Ajit Kumar
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Gear Up for the Journey

About this book

Sencha Touch is one of the most popular HTML5 and JavaScript frameworks for building touch-based mobile devices. Using Sencha Touch, you can create applications for touch mobile devices with ease, and once created, the same application works on multiple platforms – iOS, Android, Blackberry – without having to change anything.

Sencha Touch Cookbook, Second Edition is a practical, hands-on guide with easy to follow recipes that provide you with clear, step-by-step instructions, which will help you take complete advantage of the power of Sencha Touch 2 and will help you to build amazing applications for the mobile world.

Sencha Touch Cookbook, Second Edition starts by showing you how to set up your project for development, then walks through building, packaging, and running it in a browser, emulator, or a real device. With the groundwork set, the subsequent recipes of the book take you through the different UI components offered by the framework and explains how to use them, when to use them, and, if needed, how to extend them for your own application need.

You will also learn how to model your client side data, load data from different data sources, and use them on the data-centric UI components. The later parts of the book cover the practical day-to-day problems like how to create a custom view, how to take your application offline and support automatic sync, how to utilize the Geolocation to learn more about the user, how to utilize device features such as camera, contact, orientation, and how to link your application behaviour with the device buttons such as Back, Search, and so on. At the end, the book shows you how to create native packages without using PhoneGap/Cordova using Sencha Cmd.

Using this book, you will learn everything about using Sencha Touch classes and components to build mobile applications that can run across multiple platforms.

Publication date:
August 2013
Publisher
Packt
Pages
418
ISBN
9781782169185

 

Chapter 1. Gear Up for the Journey

In this chapter we will cover:

  • Setting up the Android-based development environment

  • Setting up the iOS-based development environment

  • Setting up the BlackBerry-based development environment

  • Setting up a browser-based development environment

  • Detecting the device

  • Finding features that are supported in the current environment

  • Letting your application configure itself using profiles

  • Responding to orientation changes

 

Introduction


As with any other development, the first and foremost thing that is required before we embark on our journey is setting up the right environment so that development, deployment, and testing become easier and effective. And this calls for a list of tools that are appropriate in this context. In this chapter, we will cover topics related to setting up the environment using the right set of tools. Sencha Touch is an HTML5-based JavaScript framework to build applications for touch devices. An application built using Sencha Touch can be accessed from a web browser or can be packaged for the target touch device and run on it. Sencha Touch 2.2 supports WebKit, the IE 10 browser on Windows 8, and the following platforms:

  • Android

  • iOS

  • BlackBerry

  • Windows Phone 8

For each of these platforms, we will see what steps we need to follow to set up the complete development and deployment environment. We will be packaging our Sencha Touch-based application using Apache Cordova. Cordova is another JavaScript framework, which provides two important capabilities:

  • The APIs needed to access the device features, such as camera and address book

  • A build mechanism for writing the code once (in the form of JS, HTML and CSS) and packaging them for different platforms such as iOS and Android

Throughout the book we will be using the following software:

  • Sun JDK version 1.5 or above (required to run Eclipse)

  • Android Developer Tools (ADT-bundled Eclipse), which is required for Android development

  • Apache Cordova 2.4.0 (required for using device features and packaging the application for different platforms)

  • Apache Ant 1.8.4 or above (required to run a project build in Eclipse and Cordova tools)

  • Sencha Touch 2.2.1 library (Sencha Touch SDK)

  • Xcode 4 (required for iOS development)

  • BlackBerry WebWorks SDK (required for BlackBerry development)

Before we get any further, you should download and install the following, which will act as a common base for all our discussions:

  • Sun JDK 1.5 or above

  • Android Developer Tools (ADT-bundled Eclipse)

  • Sencha Touch 2.2.1 library

After downloading Sencha Touch library, extract it to a folder, say, C:\sencha-touch-cookbook\softwares\touch-2.2.1. After the extraction, you should see the folders as shown in the following screenshot:

There are many files that are not required for the development and testing.

Note

The docs folder contains the documentation for the library and is very handy when it comes to referring to the properties, configs, methods, and events supported by different classes. You may want to copy it to a different folder so that you can refer to the documentation whenever needed.

Since there are many files inside the SDK, let us clean it up a bit so that we remove the files that are not required for development. Delete the files and folders enclosed within the rectangles in the following screenshot:

This prepares us to get started. Since Sencha Touch is a JavaScript library, you may want to configure your Eclipse installation for JavaScript development. You may install the VJET and Sencha Eclipse plugin, which comes with Sencha Complete, and configure it for Sencha Touch development. Steps to do so are detailed on the VJET website (http://eclipse.org/vjet/) and instructions are provided as part of the Sencha Complete package; hence, they have been excluded from this book. To learn more about Sencha Complete, visit http://www.sencha.com/products/complete.

Download and install Apache Ant from http://ant.apache.org/ to a folder of your choice, say, C:\sencha-touch-cookbook\softwares\apache-ant-1.8.4, and add this as the ANT_HOME environment variable. Also, add %ANT_HOME%\bin to the PATH environment variable.

Note

To learn about device and platform support, you may refer to http://www.sencha.com/products/touch/features/ to see if your device and platform are listed.

 

Setting up the Android-based development environment


This recipe describes the detailed steps we need to follow to set up the environment for the Android-based development. The steps do not include setting up the production environment.

Getting ready

Install JDK and set the following environment variables correctly:

  • JAVA_HOME

  • PATH

Install Apache Ant and set the following environment variables correctly:

  • ANT_HOME

  • PATH

How to do it...

Follow these steps to set up your Android-based development environment:

  1. Download Android SDK ADT Bundle for your platform from http://developer.android.com/sdk/index.html and install it inside the softwares folder, C:\sencha-touch-cookbook\softwares\adt-bundle-windows-x86_64.

  2. The installed folder contains two folders, sdk and eclipse. sdk contains Android SDK whereas eclipse contains ADT-bundled Eclipse.

  3. Add the following folder paths to the PATH environment variable:

    • platform-tools

    • tools

  4. Download Apache Cordova from http://cordova.apache.org/ and extract it to a folder or your choice, say, C:\sencha-touch-cookbook\softwares\cordova-2.4.0. We will refer to this as CORDOVA_HOME.

  5. Go to the CORDOVA_HOME folder and extract the following in it:

    • cordova-android: This is an Android application library that allows for Cordova-based projects to be built for the Android platform

    • cordova-cli: This is the command-line tool to build, deploy, and manage Cordova-based applications

    • cordova-js: This contains a unified JavaScript layer for Cordova-based projects

  6. Launch the command prompt and go to <CORDOVA_HOME>\cordova-android\bin.

  7. Run the following command to create our project:

    create c:\sencha-touch-cookbook\projects\SenchaTouch com.senchatouch.book SenchaTouch
    

    You shall see the following messages, which shows that everything went well:

    The syntax of the command create <project folder> <default package> <project name>.

  8. This will create a SenchaTouch folder inside the projects folder.

  9. Go to the eclipse folder inside the ADT installed folder.

  10. Launch Eclipse and use C:\sencha-touch-cookbook\workspace as the workspace folder.

  11. Click on the File menu and select Import. Select Existing Android Code Into Workspace under the Android section.

  12. Click on the Next button; this will take you to the Import Projects window. Click on the Browse... button, next to Root Directory, and select the SenchaTouch project that we created in the previous step.

  13. Click on the Finish button to import the project.

  14. Expand the assets\www folder and delete the files as shown in the following screenshot:

  15. Copy the www directory and located at C:\sencha-touch-cookbook\softwares\touch-2.2.1 folder to the assets directory and rename it to touch.

  16. Create and open a new file named ch01_01.js file in the assets/www/ch01 directory. Paste the following code in it:

    Ext.application({
        name: 'MyApp',
    
        launch: function() {
        Ext.Msg.alert("INFO", "Welcome to the world of Sencha Touch!");
        }
    });
  17. Now create and open a new file named index.html in the assets\www directory. Paste the following code in it:

    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Sencha Touch Cookbook - Sample</title>
    <link rel="stylesheet" href="touch/resources/css/sencha-touch.css" type="text/css">
    <script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="touch/sencha-touch-all-debug.js"></script>
    <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script>
    </head>
    <body></body>
    </html>
  18. Deploy the project to the simulator:

    1. Right-click the project, go to Run As, and click on Android Application.

    2. Eclipse will ask you to select an appropriate AVD. If there isn't one, you'll need to create it. To create an AVD, follow these steps:

      1. In Eclipse, go to Window | Android Virtual Device Manager.

      2. Select the Android Virtual Devices tab and click on the New… button.

      3. Enter your virtual device detail. For example, the following screenshot shows the virtual device detail for the Samsung Galaxy Ace running Android 2.2:

      4. Click on the OK button.

  19. Deploy the project to the device:

    1. Make sure USB debugging is enabled on your device and plug it into your system. You may enable it by going to Settings | Applications | Development.

    2. Right-click on the project, go to Run As, and click Android Application. This will launch the Android Device Chooser window.

    3. Select the device and click on the OK button.

With these steps, now you will be able to develop and test your application.

How it works...

From steps 1 to 5, we downloaded and installed Android SDK, the ADT-bundled Eclipse plugin, and Apache Cordova, which are required for the development of the Android-based application. The SDK contains the Android platform-specific files, an Android emulator, and various other tools required for the packaging, deployment, and running of Android-based applications. The ADT plugin for Eclipse allows us to create Android-based applications and to build, test, and deploy them using Eclipse.

In steps 6 and 7, we created an Android project using Apache Cordova's command-line utility. It creates a project that is completely compatible with the ADT plugin.

From steps 9 to 13, we imported the Cordova-created project into the ADT-bundled Eclipse.

In steps 14 and 15, we removed the unwanted files and folders and copied Sencha Touch SDK to the www folder of the project. This is required to run the touch-based applications. We kept the Cordova JavaScript file, which contains the implementation of the Cordova APIs. You shall do this if you intend to use the Cordova APIs in your application (for example, to get the contacts list in your application). For this book, this is an optional step; however, interested readers may find details about the API at http://docs.phonegap.com/en/2.4.0rc1/index.html.

In step 16, we created the ch01_01.js JavaScript file that contains the entry point for our Sencha Touch application. The Ext.application class registers the launch function as the entry point to the application, which the framework calls during the application startup.

In step 17, we modified the index.html file to include the Sencha-Touch-related JavaScript (sencha-touch-all-debug.js), CSS files (sencha-touch.css) and our application-specific JavaScript files (ch01_01.js). sencha-touch-all-debug.js is very useful during development as it contains well-formatted code, which can be used to analyze application errors during development. You also need to include the Cordova JS file in case you intend to use its APIs in your application. The Cordova-related JS and CSS files need to be included first, then come Sencha-Touch-related JS and CSS files, and finally the application-specific JS and CSS files.

In step 18, we created an Android virtual device (an emulator) and deployed and tested the application on it.

Finally, in step 19, we deployed the application on a real Android 2.2-compatible device.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

 

Setting up the iOS-based development environment


This recipe outlines the steps to set up the development environment for the iOS-based (for example, iPhone, iPad, and iPod) development.

Getting ready

Install JDK and set the following environment variables correctly:

  • JAVA_HOME

  • PATH

Install Apache Ant and set the following environment variables correctly:

  • ANT_HOME

  • PATH

You should have created the ch01_01.js file as mentioned in the previous recipe.

Download and install Xcode from Apple Developer portal at http://developer.apple.com. This requires you to have membership of the iOS and Mac developer programs.

How to do it...

Follow these steps to set up your iOS-based development environment:

  1. Launch Xcode and go to Preferences. Click on the Downloads tab on the top and install Command Line Tools, as shown in the following screenshot:

  2. Exit Xcode.

  3. Download Apache Cordova from http://cordova.apache.org/ and extract it to a folder or your choice, say, C:\sencha-touch-cookbook\softwares\cordova-2.4.0. We will refer to this as CORDOVA_HOME.

  4. Go to the CORDOVA_HOME folder and extract the following in it:

    • cordova-ios: This is an iOS application library that allows for Cordova-based projects to be built for the iOS platform

    • cordova-cli: This is the command-line tool to build, deploy, and manage Cordova-based applications

    • cordova-js: This contains a unified JavaScript layer for Cordova-based projects

  5. Launch the Terminal window and go to <CORDOVA_HOME>\cordova-ios\bin.

  6. Run the following command to create your project:

    create ~\sencha-touch-cookbook\projects\SenchaTouchiOS com.senchatouch.book SenchaTouchiOS
    

    This will create a project inside the ~\sencha-touch-cookbook\projects\SenchaTouchiOS folder.

  7. Use Finder and get to the SenchaTouchiOS folder created in the previous step.

  8. Double-click on SenchaTouchiOs.xcodeproj to open the project in Xcode, as shown in the following screenshot:

    In Finder, you should see the www directory inside your project.

  9. Copy the touch-2.2.1 folder inside www and rename it to touch.

  10. Add the ch01 folder to www and copy the ch01_01.js file in it, which was created in the previous recipe.

  11. Open the folder named www and paste the following code in the index.html file:

    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Sencha Touch Cookbook - Sample</title>
    <link rel="stylesheet" href="touch/resources/css/sencha-touch.css" type="text/css">
    <script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="touch/sencha-touch-all-debug.js"></script>
    <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script>
    </head>
    <body></body>
    </html>
  12. Deploy the project to simulator:

    Make sure you change the simulator on the top-left menu and hit Run in your project window header. This will build and run the project in the simulator, as shown in the following screenshot:

  13. Deploy the project to a device:

    1. Create a provisioning profile on http://developer.apple.com/iphone/manage/overview/index.action.

    2. Verify that the Code Signing Identity option in the Code Signing sections of the SenchaTouchiOS Xcode project settings has been set with your provisioning profile name.

    3. Connect your device using USB or Thunderbolt.

    4. Make sure to select the device on the top-left corner, as shown in the following screenshot:

    5. Hit Run in your project window header.

How it works...

In steps 2 and 3, we installed the required tools and libraries in Xcode. It is the IDE provided by Apple for the iOS-based application development.

From steps 3 to 6, we created a Cordova-based iOS project using Cordova's command-line utility.

From steps 7 to 10, we prepared the www folder for the application. Its content is described in the Setting up the Android-based development environment recipe.

In step 11, we included the Sencha Touch-related files and the application-specific JS file (ch01_01.js) in the index.html file.

In step 12 and 13, we deployed and tested the application in the simulator as well as a real iOS device (for example, iPhone).

See also

  • The Setting up the Android-based development environment recipe

 

Setting up the BlackBerry-based development environment


So far, we have seen how to set up the environments for Android and iOS development. This recipe walks us through the steps required to set up the environment for BlackBerry-based development.

Getting ready

Install JDK and set the following environment variables correctly:

  • JAVA_HOME

  • PATH

Install Apache Ant and set the following environment variables correctly:

  • ANT_HOME

  • PATH

You should have created the ch01_01.js file as mentioned in the previous recipe.

How to do it...

Follow these steps to set up your BlackBerry-based development environment:

  1. Download BlackBerry WebWorks SDK from http://developer.blackberry.com/html5/download/ and install it to, say, C:\sencha-touch-cookbook\softwares\RIM\BlackBerry10WebWorksSDK1.0.4.11.

  2. Download and install the BlackBerry simulator from http://developer.blackberry.com/develop/simulator/simulator_installing.html.

  3. Go to the CORDOVA_HOME folder and extract the following into it:

    • cordova-blackberry: This is a BlackBerry application library that allows for Cordova-based projects to be built for the BlackBerry platform

    • cordova-cli: This is the command-line tool to build, deploy, and manage Cordova-based applications

    • cordova-js: This contains a unified JavaScript layer for Cordova-based projects

  4. Launch the command prompt and go to <CORDOVA_HOME>\cordova-ios\bin.

  5. Run the following command to create your project:

    create ~\sencha-touch-cookbook\projects\SenchaTouchBB com.senchatouch.book SenchaTouchBB
    

    This will create a project inside the ~\sencha-touch-cookbook\projects\SenchaTouchBB folder.

  6. Go to c:\sencha-touch-cookbook\projects\SenchaTouchBB, edit project.properties in an editor of your choice, and set the following properties:

    blackberry.bbwp.dir=C:\\sencha-touch-cookbook\\softwares\\RIM\\BlackBerry10WebWorksSDK1.0.4.11
  7. Copy the touch-2.2.1 folder inside www and rename it to touch.

  8. Add the ch01 folder to www, and copy the ch01_01.js file inside it, which was created in the previous recipe.

  9. Open the folder named www and paste the following code in the index.html file:

    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Sencha Touch Cookbook - Sample</title>
    <link rel="stylesheet" href="touch/resources/css/sencha-touch.css" type="text/css">
    <script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="touch/sencha-touch-all-debug.js"></script>
    <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script>
    </head>
    <body></body>
    </html>
  10. Run the command window and go to the SenchaTouchBB project folder.

  11. Run the following command to build the project:

    ant blackberry build

    This will create the .bar file for the device as well as a simulator; these are kept under the build folder inside the SenchaTouchBB folder.

  12. Deploy the project to the simulator:

    1. Download and install the VMware player from http://www.vmware.com/products/player/.

    2. Run the simulator file, based on your platform, using the VMware player. Make a note of the IP address of the simulator.

    3. Go to C:\sencha-touch-cookbook\softwares\RIM\BlackBerry10WebWorksSDK1.0.4.11\dependencies\tools\bin and run the following command on the command prompt:

      blackberry-deploy –installApp –device <ip address of simulator> -package C:\sencha-touch-cookbook\projects\SenchaTouchBB\build\simulator\SenchaTouchBB.bar
      
    4. This will deploy the application on the simulator and you shall be able to launch it by tapping on the icon.

  13. Deploy the project to the device:

    1. You have to have your signing keys from RIM.

    2. Plug in your device to the computer.

    3. While in your project directory, in the command prompt, type ant blackberry load-device.

How it works...

In steps 1 and 2, we downloaded and installed the BlackBerry SDK and Apache Cordova, required for the BlackBerry-based development.

In steps 3 to 5, we created a Cordova-based project for BlackBerry.

In step 6, we set up the BlackBerry SDK path, which will be used by the Cordova build and deploy scripts.

From steps 7 to 9, we prepared the www folder by creating and copying our application-specific folders and files. Also, we modified the index.html file to make it look exactly like the one created in the Setting up the Android-based development environment recipe.

In steps 10 and 11, we built the project and created the deployable packages for the BlackBerry simulator as well as the device.

In steps 12 and 13, we deployed and tested the application in the simulator as well as a real BlackBerry device.

See also

  • The Setting up the Android-based development environment recipe

 

Setting up a browser-based development environment


In the previous recipes, we saw how we can make use of Cordova to build, package, and deploy the Sencha Touch applications directly on the device. Another very popular kind of application is the browser-based one. All the devices, which Sencha Touch supports come along with Internet browsers. In this recipe, we will see how we can develop a Sencha Touch application, access it, and test it using Internet browsers.

Sencha Touch is moving towards using HTML5 features and we will require a browser that runs on WebKit engine: Opera, Safari, and Chrome or the IE 10 browser. We can also test most of the things on a browser running on your desktop/workstation (except items such as orientation change).

Note

Sencha Touch applications do not work on the browsers using the Gecko engine, which includes Mozilla Firefox.

We will be using this environment for this book to demonstrate the capabilities of Sencha Touch.

Getting ready

Make sure your device has a WebKit-compatible browser, such as Opera, Safari, and Chrome or IE 10.

Verify that you have your GPRS or Wi-Fi enabled and working on your device so that you are able to access the Internet.

You should have a web server (such as Apache or nginx) deployed on a server, which is accessible on the Internet. For example, I have my web server running on http://walkingtree.in.

How to do it...

Follow these steps to set up your browser-based development environment:

  1. Create a folder touch-cookbook in your web server's deployment/root folder, say, public_html or htdocs.

  2. Copy the content of the assets\www folder, prepared in the Setting up the Android-based development environment recipe, to the touch-cookbook folder.

  3. Go to the Internet browser on your device and enter the http://<your domain or ip address>:<port>/touch-cookbook URL (for example, http://walkingtree.in/touch-cookbook) in the address bar and hit Go. You should have the application running inside the browser, as shown in the following screenshot:

How it works...

In step 1, we created the touch-cookbook folder as a placeholder to keep our application code inside it. This would help us avoid polluting the web server's root folder.

In step 2, we copied the contents from the assets\www folder, which we prepared in the Setting up the Android-based development environment recipe. In step 3, we removed the <script> tag including the Cordova JS file, as we are not going to use its APIs in this book.

See also

  • The Setting up the Android-based development environment recipe

 

Detecting the device


Different devices offer different capabilities; hence, for an application developer, it becomes important to identify the exact device so that it can respond to the events in the most appropriate way. Sencha Touch offers the Ext.os class to help us detect the platform or device. This recipe describes how we can detect the device on which the application is being run using this class.

How to do it...

Follow these steps:

  1. Create and open a new file ch01_02.js in the ch01 folder and paste the following code into it:

    Ext.application({
        name: 'MyApp',
        launch: function() {
    
      if (Ext.os.is.Android)
      Ext.Msg.alert("INFO", "Welcome Android user!");
    
      if (Ext.os.is.Blackberry)
      Ext.Msg.alert("INFO", "Welcome Blackberry user!");
      
      if (Ext.os.is.iPad)
      Ext.Msg.alert("INFO", "Welcome iPad user!");
    
      if (Ext.os.is.Windows) {
        var str = "Welcome Windows user!";
        if (Ext.os.deviceType === "Desktop")
          str += "Looks like you are running this sample on Desktop";
    
        Ext.Msg.alert("INFO", str);
      }
        }
    });
  2. Remove the following line from index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script>
  3. Include the following line in index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_02.js"></script>
  4. Deploy and run the application. Based on the device on which the application is being run, you will see a corresponding message.

How it works...

The Ext.os class is instrumental in detecting your target device platform on which your application is being run. It uses the JavaScript's navigator object to detect the browser details, including the platform/device. For example, if the platform property in the navigator object has iPhone in it, the target platform is iPhone; whereas, if the userAgent property in the navigator object has Android, the platform is Android.

See also

  • The Setting up a browser-based development environment recipe

 

Finding features that are supported in the current environment


Each device and platform offers a rich set of functionality. However, it is difficult to identify a set of features available across all devices and platforms. And even if we happen to find out a list of common features, there may be reasons why you may want to use a feature on a device that is not present on other devices; here, you would make your application work on those devices by creating the best approximation of that specific feature. For example, on a device where SVG is supported, you may want to make use of that feature in your application to render the images so that they are scalable. However if another device does not support SVG, you may want to fall back to rendering your image into JPEG/PNG so that the image will be visible to the user. This recipe describes how an application can detect the different features that a device supports. This comes in very handy to enable/disable certain application features based on the device's supported features.

How to do it...

Follow these steps:

  1. Create and open a new file ch01_03.js in the ch01 folder and paste the following code in it:

    Ext.application({
        name: 'MyApp',
    
        launch: function() {
    
          var featuresStr = "";
          for (var key in Ext.feature.has) {
            if (Ext.feature.has.hasOwnProperty(key))
            featuresStr += key + " - " + Ext.feature.has[key] + "\n";
          }
    
          var browserStr = "";
          for (var key in Ext.browser.is) {
            if (Ext.browser.is.hasOwnProperty(key))
            browserStr += key + " - " + Ext.browser.is[key] + "\n";
          }
    
          alert(featuresStr);
          alert(browserStr);
        }
    });
  2. Remove the following line from index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_02.js"></script>
  3. Include the following line in index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_03.js"></script>
  4. Deploy and run the application. Based on the device on which the application is being run, you will see a corresponding message.

How it works...

Check that the support for different features is encapsulated inside the Sencha Touch's Ext.feature class. This class applies various different mechanisms to find out whether a requested feature is supported by the target platform/device. For example, to find out whether the device supports geolocation, this class checks whether geolocation is present in the window object. Another example to find out whether SVG is supported on the target platform is that it tries to add an SVG element (removed after successful creation, setting the flag to indicate that the device supports SVG) to the document.

The Ext.browser class helps us detect which browser we are running on.

In the code, we are iterating through the various properties of the Ext.feature and Ext.browser class and showing the value of each property, based on the device that we are running our application on.

See also

  • The Setting up a browser-based development environment recipe

 

Letting your application configure itself using profiles


This recipe describes how to set up multiple profiles for an application and let the application configure itself using the profile.

How to do it...

Follow these steps:

  1. Create and open a new file ch01_04.js in the ch01 folder and paste the following code in it:

    Ext.application({
        name: 'MyApp',
       profiles: ['Android', 'Desktop', 'TabletPortrait'],
        launch: function() {
      Ext.Viewport.add(Ext.create('Ext.Panel', {
                items : [
                    {
                        html: 'Welcome to My App!' + ' - profile - ' + this.getCurrentProfile().getName()
                    }
                ]
            }));
        }
    
    });
  2. Create an app folder inside the www folder and a profile folder under it.

  3. Create and open a new file Android.js in the profile folder and paste the following code in it:

    Ext.define('MyApp.profile.Android', {
        extend: 'Ext.app.Profile',
    
        isActive: function() {
            return Ext.os.is.Android;
        }
    });
  4. Create and open a new file Desktop.js in the profile folder and paste the following code in it:

    Ext.define('MyApp.profile.Desktop', {
        extend: 'Ext.app.Profile',
    
        isActive: function() {
            return Ext.os.deviceType === 'Desktop';
        }
    });
  5. Create and open a new file TabletPortrait.js in the profile folder and paste the following code in it:

    Ext.define('MyApp.profile.TabletPortrait', {
        extend: 'Ext.app.Profile',
    
        isActive: function() {
            return Ext.os.deviceType === 'Tablet' && Ext.viewport.Default.getOrientation() === 'portrait';
        }
    });
  6. Remove the following line from index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_03.js"></script>
  7. Include the following line in index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_04.js"></script>
  8. Deploy and run the application. Based on the device profile, you shall see a message.

How it works...

The Application class provides a property profiles, which is used to set up multiple profiles, as shown in the previous code. When the application is launched, the framework calls the isActive method of each of the profile classes; whichever method returns true, that profile becomes active and is used in the application.

In the previous code, we defined three profile classes Android, Desktop, and TabletPortrait, where the isActive method does a profile-specific check and returns true or false.

The current profile can be fetched from the application; you can use the getCurrentProfile() method, which returns the instance of Ext.app.Profile; then we call the getName() method on it to print the name of the profile (for example, Android). The name property is the name of the profile class name.

See also

  • The Setting up a browser-based development environment recipe

 

Responding to orientation changes


It is possible to change the orientation from portrait mode to landscape by turning your device. Many applications make use of this to provide better usability to the user. For example, when we are working with the virtual keyboard and change the orientation from portrait to landscape, the keyboard gets bigger and it becomes easier to type. Most of the devices support orientation change; based on your application, you may want to make use of this feature to change your application layout or behavior. Sencha Touch automatically watches for this and notifies all the application components by sending them the orientationchange event. The framework fires the orientationchange event on the Ext.Viewport class that needs to be handled in case we want to modify the behavior of our application when the orientation of the device changes.

If the application or any component of it needs to change its behavior, the corresponding component shall register a handler for the orientationchange event.

How to do it...

Follow these steps:

  1. Create and open a new file ch01_05.js in the ch01 folder and paste the following code in it:

    Ext.application({
        name: 'MyApp',
        launch: function() {
      Ext.Viewport.add(Ext.create('Ext.Panel', {
                items : [
                    {
                        html: 'Welcome to My App!'
                    }
                ],
      listeners: {
        orientationchange: function(vp, newOrientation, width, height, eOpts) {
          Ext.Msg.alert("INFO","Orientation: " + newOrientation + " : width:" + width + ":height:" + height);
        }  
      }
            }));
        }
    
    });
  2. Remove the following line from index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_04.js"></script>
  3. Include the following line in index.html:

    <script type="text/javascript" charset="utf-8" src="ch01/ch01_05.js"></script>
  4. Deploy and run the application. Based on the device orientation, you shall see a message.

How it works...

The Viewport class in Sencha Touch framework registers the orientationchange event and resizes the event handler if the target platform supports it. These handlers are invoked when the device orientation is changed. It also checks the autoMaximize property, which is by default set to false, and auto maximizes the viewport (and the application) when the orientation changes. The handlers, after resizing or maximizing the application, fire the orientationchange event that is available to the application developers on the Viewport class to handle and further modify the application behavior, if needed.

See also

  • The Setting up a browser-based development environment recipe

About the Author

  • Ajit Kumar

    Ajit Kumar has over 16 years of experience in technology areas ranging from embedded systems to large enterprise applications. He worked with various multinational corporations such as Honeywell, Hughes, Virtusa, and Convergys, before starting his own company—Walking Tree—which specializes in Sencha frameworks.

    Ajit has authored books on open source frameworks, including Sencha Touch Cookbook, Sencha Touch Cookbook Second Edition, Sencha MVC Architecture, and ADempiere 3.6 Cookbook, all by Packt Publishing, which he considers his way of thanking the awesome open source community!

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now