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.


No comments:

Post a Comment