Thursday, August 2, 2012

Secnha Touch 2: Model-View-Controller Architecture [part 2]

Controllers are the glue the binds an application together. They listen for events fired by the UI and then take some action on it. This helps to keep our code clean and readable, and separates the view logic from the control logic.
For example, let's say you require users to log in to your app via a login form. The view in this case is the form with all of its fields and other controls. A controller should listen to tap event on the form's submit button and then perform the authentication itself. Any time we deal with manipulating data or state, the controller should be the class that activates that change, not a view.
Controllers expose a small but powerful set of features, and follow a few simple conventions. Each Controller in your application is a subclass of (though you can subclass existing Controllers, so long as it inherits from at some point). Controllers exist in the MyApp.controller.* namespace - for example if your app had a Sessions controller it would be called MyApp.controller.Sessions and exist in the file app/controller/Sessions.js.
Although each Controller is a subclass of, each one is instantiated just once by the Application that loaded it. There is only ever one instance of each Controller at any one time and the set of Controller instances is managed internally by the Application. Using Application's controllersconfig (as we do above) loads all of the Controllers and instantiates them automatically.

Here's how we might quickly define the Sessions controller described above. We're using 2 Controller configurations here - refs and control. Refs are an easy way to find Components on your page - in this case the Controller will look for all Components that match the formpanel xtype and assign the first one it finds to the loginForm property. We'll use that property in the doLogin function later.
The second thing it does is set up a control configuration. Just like refs, this uses a ComponentQuery selector to find all formpanel xtypes that contain abutton inside them (for example, this will find the Submit button in our hypothetical login form). Whenever any button of this type fires its tap event, our Controller's doLogin function will be called:

Ext.define('MyApp.controller.Sessions', {
    extend: '',

    config: {
        refs: {
            loginForm: 'formpanel'
        control: {
            'formpanel button': {
                tap: 'doLogin'

    doLogin: function() {
        var form   = this.getLoginForm(),
            values = form.getValues();


The doLogin function itself is quite straightforward. Because we defined a 'loginForm' ref, the Controller automatically generates a getLoginForm function that returns the formpanel that it matches. Once we have that form reference we just pull the values (username and password) out of it and pass them to an authenticate function. That's most of what Controllers ever do - listen for events fired (usually by the UI) and kick off some action - in this case authenticating.

Device Profiles
Stores are an important part of Sencha Touch and power most of the data-bound widgets. At its simplest, a Store is not much more than an array of Model instances. Data-bound Components like List and DataView just render one item for each Model instance in the Store. As Model instances are added or removed from the Store events are fired, which the data-bound Components listen to and use to update themselves.
While the Stores guide has much more information on what Stores are and how they fit in with Components in your app, there are a couple of specific integration points with your Application instance that you should be aware of.
Sencha Touch operates across a wide range of devices with differing capabilities and screen sizes. A user interface that works well on a tablet may not work very well on a phone and vice versa so it makes sense to provide customized views for different device types. However, we don't want to have to write our application multiple times just to provide a different UI - we'd like to share as much code as possible.
Device Profiles are simple classes that enable you to define the different types of devices supported by your app and how they should be handled differently. They are opt-in, so you can develop your app without profiles at first and add them in later, or never use them at all.Each profile simply defines an isActive function that should return true if that profile should be active on the current device, plus a set of additional modelsviews andcontrollers to load if that profile is detected.
To app Profile support to your app you just need to tell your Application about those Profiles and then create subclasses for them:
    name: 'MyApp',
    profiles: ['Phone', 'Tablet'],

    //as before
By defining the profiles above the Application will load app/profile/Phone.js and app/profile/Tablet.js. Let's say that the tablet version of the app enables additional capabilities - for example managing groups. Here's an example of how we might define the Tablet profile:
Ext.define('MyApp.profile.Tablet', {
    extend: '',

    config: {
        controllers: ['Groups'],
        views: ['GroupAdmin'],
        models: ['MyApp.model.Group']

    isActive: function() {
The isActive function will return true whenever the application is run on what Sencha Touch determines to be a tablet. This is a slightly subjective determination because there is a near-continuous spectrum of device shapes and sizes with no clear cutoff between phones and tablets. Because there is no foolproof way to state which devices are tablets and which are phones, Sencha Touch's is set to true when running on an iPad and false otherwise. If you need more fine grained control it's easy to provide any implementation you like inside your isActive function, so long as it returns true or false.
You should make sure that only one of your Profiles returns true from its isActive function. If more than one of them returns true, only the first one that does so will be counted and the rest ignored. The first one that returns true will be set as the Application's currentProfile, which can be queried at any time.
If the detected currentProfile has defined additional models, views, controllers and stores these will be automatically loaded by the Application, along with all of the modelsviews and controllers defined on the Application itself. However, all of the dependencies named in the Profile will be prepended with the Profile name unless the fully-qualified class name is provided. For example:

  • views: ['GroupAdmin']
  •  will load app/view/tablet/GroupAdmin.js
  • controllers: ['Groups']
  •  will load app/controller/tablet/Groups.js
  • models: ['MyApp.model.Group']
  •  will load app/model/Group.js

Sum it up
  1. Controller#init functions called
  1. Profile#launch function called
  1. Application#launch function called
  1. Controller#launch functions called

Each Application can define a launch function, which is called as soon as all of your app's classes have been loaded and the app is ready to be launched. This is usually the best place to put any application startup logic, typically creating the main view structure for your app.
In addition to the Application launch function, there are two other places you can put app startup logic. Firstly, each Controller is able to define an initfunction, which is called before the Application launch function. Secondly, if you are using Device Profiles, each Profile can define a launch function, which is called after the Controller init functions but before the Application launch function.
Note that only the active Profile has its launch function called - for example if you define profiles for Phone and Tablet and then launch the app on a tablet, only the Tablet Profile's launch function is called.
When using Profiles it is common to place most of the bootup logic inside the Profile launch function because each Profile has a different set of views that need to be constructed at startup.


Sencha Touch 2: Wrapping all up [part 2]

  • Your AndroidManifest.xml file should look like

Hello World

Create and open a new file named index.html in the assets/www directory. Paste the following code:

<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<h1>Hello World</h1>

Deploy to Simulator

  • Right click the project and go to Run As > Android Application
  • Eclipse will ask you to select an appropriate AVD. If there isn't one, then you'll need to create it.

Deploy to Device

  • Make sure USB debugging is enabled on your device and plug it into your system. (Settings > Applications > Development)
  • Right click the project and go to Run As > Android Application

Sencha Touch 2: The Basics [Part 4]

The last part of the proxy definition was a Reader. The reader is what decodes the response from Google into useful data. When Google sends us back the blog data, they nest it inside a JSON object that looks a bit like this:
    responseData: {
        feed: {
            entries: [
                {author: 'Bob', title: 'Great Post', content: 'Really good content...'}
The bit we care about is the entries array, so we just set our Reader's rootProperty to 'responseData.feed.entries' and let the framework do the rest.
Now that we have our nested list fetching and showing data, the last thing we need to do is to allow the user to tap on an entry to read it. We're just going to add two more configurations to our Nested List to finish this off:

    xtype: 'nestedlist',
    //all other configurations as above

    detailCard: {
        xtype: 'panel',
        scrollable: true,
        styleHtmlContent: true

    listeners: {
        itemtap: function(nestedList, list, index, element, post) {
Here we've just set up a detailCard, which is a useful feature of Nested List that allows you to show a different view when a user taps on an item. We've configured our detailCard to be a scrollable Panel that uses styleHtmlContent to make the text look good.
The final piece of the puzzle is adding an itemtap listener, which just calls our function whenever an item is tapped on. All our function does is set the detailCard's HTML to the content of the post you just tapped on and the framework takes care of the rest, animating the detail card into view to make the post appear. This was the only line of code we had to write to make the blog reader work.
The final thing we're going to do for our app is create a contact form. We're just going to take the user's name, email address and a message, and use aFieldSet to make it look good. The code for this one is simple:
    name: 'Sencha',

    launch: function() {
        Ext.create("", {
            fullscreen: true,
            tabBarPosition: 'bottom',

            items: [
                    title: 'Contact',
                    iconCls: 'user',
                    xtype: 'formpanel',
                    url: 'contact.php',
                    layout: 'vbox',

                    items: [
                            xtype: 'fieldset',
                            title: 'Contact Us',
                            instructions: '(email address is optional)',
                            items: [
                                    xtype: 'textfield',
                                    label: 'Name'
                                    xtype: 'emailfield',
                                    label: 'Email'
                                    xtype: 'textareafield',
                                    label: 'Message'
                            xtype: 'button',
                            text: 'Send',
                            ui: 'confirm',
                            handler: function() {
This time we're just creating a form that contains a fieldset. The fieldset contains three fields - one for name, one for email and one for a message. We've using a VBox layout, which just arranges the items vertically on the page one above the other.
At the bottom we have a Button with a tap handler. This employs the useful up method, which returns the form panel that the button is inside of. We then just call submit to submit the form, which sends it to the url we specified above ('contact.php').


Sencha Touch 2: The Basics [Part 3]

Adding the blogs page

Now that we have a decent looking home page, it's time to move on to the next screen. In order to keep the code for each page easy to follow we're just going to create one tab at a time and then combine them all together again at the end.
For now, we'll remove the first tab and replace it with a List. We're going to be using Google's Feed API service to fetch the feeds.
Instead of a panel we're using a nestedlist this time, fetching the most recent blog posts from We're using Nested List so that we can drill down into the blog entry itself by simply tapping on the list.
Let's break down the code above, starting with just the list itself:
    name: 'Sencha',

    launch: function() {
        Ext.create("", {
            fullscreen: true,
            tabBarPosition: 'bottom',

            items: [
                    xtype: 'nestedlist',
                    title: 'Blog',
                    iconCls: 'star',
                    displayField: 'title',

                    store: {
                        type: 'tree',

                        fields: [
                            'title', 'link', 'author', 'contentSnippet', 'content',
                            {name: 'leaf', defaultValue: true}

                        root: {
                            leaf: false

                        proxy: {
                            type: 'jsonp',
                            url: '',
                            reader: {
                                type: 'json',
                                rootProperty: 'responseData.feed.entries'
We're giving the Nested List a few simple configurations - title, iconCls and displayField - and a more detailed one called store. The Store config tells the nested list how to fetch its data. Let's go over each store config in turn:
  • type: tree creates a tree store, which NestedList uses
  • fields tells the Store what fields we're expecting in the blog data (title, content, author etc)
  • proxy tells the Store where to fetch its data from. We'll examine this more closely in a moment
  • root tells the root node it is not a leaf. Above we'd set the leaf defaultValue to true so we need to override that for the root
Of all the Store configurations, proxy is doing the most work. We're telling the proxy to use Google's Feed API service to return our blog data in JSON-P format. This allows us to easily grab feed data from any blog and view it in our app (for example try swapping the Sencha blog url for above to see it fetch Slashdot's feed).

Friday, July 20, 2012

Sencha Touch 2: Wrapping all up [part 1]

Installing Cordova Template for iOS on XCode4

Installing Cordova for Android


  • Eclipse 3.4+

Install SDK + Cordova

Setup New Project

Launch Eclipse, and select menu item New > Android Project. Fill out the three panels of the New Android Project wizard shown below.

  • In the root directory of your project, create two new directories:
    • /libs
    • assets/www
  • Copy cordova-1.9.0.js from your Cordova download earlier to assets/www
  • Copy cordova-1.9.0.jar from your Cordova download earlier to /libs
  • Copy xml folder from your Cordova download earlier to /res
  • Verify that cordova-1.9.0.jar is listed in the Build Path for your project. Right click on the /libs folder and go to Build Paths/ > Configure Build Path.... Then, in the Libraries tab, add cordova-1.9.0.jar to the project. If Eclipse is being temperamental, you might need to refresh (F5) the project once again.

    Edit your project's main Java file found in the src folder in Eclipse:
  • Add import org.apache.cordova.*;
  • Change the class's extend from Activity to DroidGap
  • Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html");

  • Right click on AndroidManifest.xml and select Open With > XML Editor
  • Paste the following permissions between the <uses-sdk.../> and <application.../> tags.

        android:anyDensity="true" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    • Support orientation changes by pasting the folowing inside the <activity> tag.