Architect 2 Sencha Docs

Build Your First Mobile App

This guide shows you how to build an example mobile app using the Sencha Touch framework and the Sencha Architect development tool.

In this tutorial, we build the City Bars application, which you can use to find bars near your current position using data from the Yelp API.

This tutorial provides a working mobile application using the Sencha Touch framework, and a basic understanding of how to use Architect to build a mobile app.

An archive of this project and the accompanying CSS file are part of the GitHub examples released with Architect:

Notes

  • The tutorial in this guide provides a skeletal application to help you learn Sencha development tools. We invite you to build out the app further - and, if you do, share your results by posting them to the Architect forum.
  • Read the Sencha Architect Introduction and Guided Tour to familiarize yourself with Architect and its use.
  • You must have administrator access to your computer to install the web server portion of this tutorial and to serve your application on your computer.

Preliminary Steps

Before starting, get a web server, create a project directory, install Architect, and get a Yelp API key:

  1. Get a Web Server. Sencha recommends the free Sencha Cmd web server, which is a lightweight web server that lets you test applications on your computer. You can also use any other web server; however, if you use another web server, you need to give world write permissions to any project directories relative to the web server so that Architect can save your project in the directory.
    To install the Sencha Cmd web server:
    1. Sencha Touch requires Chrome or Safari. On a mobile device, you can use Chrome, Safari, or Internet Explorer 10.
    2. Get JRE 7. Ensure you have the Java Runtime Environment version 7. To verify, open a command line terminal and type the java -version command.
    3. Get Sencha Cmd. While at the command line, type the sencha command. If this command is not found, download and install Sencha Cmd, which provides a web server you can use to test your application from your computer.
  2. Create a Project Directory. If you are using the Sencha Cmd web server, you can locate the directory anywhere, and continue this section on Step 2.
    If you are using another web server, create the directory relative to the web server and make the directory world writable (write access for anyone or any application on your computer - this setting does not provide Internet access to your application):
    1. Mac. In Finder, right click the directory, and click Get Info. In the "Sharing & Permissions" section, change the everyone privilege to Read & Write.
    2. Ubuntu. Open a Terminal and use this command to make the directory writable:
      sudo chmod o+w .
      The sudo command prompts for your system password.
    3. Windows. Right-click the directory name, click Properties and uncheck the Read-only setting on the General tab.
  3. Install Architect. Download, install, and set up Architect.
  4. Get a Yelp API Key. Register for your free Yelp API key in the Yelp Developer Program. You need to create an account, supply the URL for a publicly available web site, explain how you want to use Yelp's API, and agree to Yelp's Terms of Use. For test purposes, the web site URL can be a top-level domain name like example.com. You need a Yelp API key to load Yelp's data into your application. The Controller section later in this guide describes how to add the Yelp data to your application.

Begin your Architect Project

To begin a project:

  1. Launch Architect
  2. Name your project
  3. Save your project
  4. Start the Sencha Cmd web server
  5. Point Architect to the URL of your web server so you can preview and test applications.

Launch Architect

To start Architect:

  1. Start Architect on your computer.
  2. Click an existing project, or for a new project, the Go button for a Sencha Touch project.
  3. Familiarize yourself with the areas described in this guide:
    AreaDescriptionView
    ToolbarProject actions. All buttons appear after you save your project

    .
    ToolboxLists Components you can drag to the Canvas or to the Project Inspector. Type the name of a property in the Filter search box to find a component quickly.

    CanvasShows the current design or code of a project.

    Project InspectorLists project classes. The name of this area is sometimes shortened to "Inspector" in other Architect guides.

    ConfigSet values for properties. Type the name of a property in the Filter search box to find a property quickly.

Name Your Project

The first step in creating an Architect project is to name the application in the Application node.

To name the application:

  1. Click Application in the Project Inspector.
  2. Click the Config tab.
  3. Under Ext.app.Application, change the name from MyApp to CityBars:

    name: CityBars

It is traditional to use a camel case name for your application name.

For more details, see Application node configuration notes.

Save Your Application

Save your project by clicking Save in the Toolbar:

Architect prompts you for the Project Name.

If you are not using the Sencha Cmd web server, the location where you save a project needs to be where your web server can serve your project. If the Save Path location doesn't point to where your web server's directory, click Browse to change directory to the directory you previously created. If you are using the Sencha Cmd web server, you can pick any directory to save your project.

In Project Name, specify the name of the project directory where you want to store your project. The Project Name value is appended to the Save Path value. Use a meaningful name - this is the name of the directory where Architect stores all the files for the project.

The convention is to use a lowercase version of the application name you assigned in the previous step so, in this case, name the folder citybars. You can use any name you choose for the directory but this convention makes it easier to to keep track of what you’re doing.

Architect 2.2 and later includes a Build button as well as a Save button. In earlier releases, clicking the Save button rebuilt the entire app, which can take a significant amount of time for a large app. In Architect 2.2, the Save button only rebuilds the application pieces that you have modified. You need to build the project before releasing it and regularly during the development cycle, but using the Save button is a fast way to preserve your work without waiting for the entire application to rebuild.

Note: Until you save a new project, only the Save button displays in the Toolbar.

If you cannot save your application, check the following:

  • Ensure that you have created a subdirectory for your projects and that the name matches the name you gave exactly; remember that this name is case sensitive.
  • Ensure that you have permissions to read and write to the directory you specified.

You can view your code at any time from within Architect. Use the Design and Code views above the left edge of the Canvas to toggle between the graphical design display and the code.

Start the Sencha Cmd Web Server

After installing Sencha Cmd, start the Sencha Cmd web server from the command line with this command and specify the folder you chose when you saved your project:

sencha fs web start -map <directory_name>
The Sencha Cmd web server serves from http://localhost:1841/directory_name where directory_name is the directory specified when you started the Sencha Cmd web server.

The web server runs exclusively in the command line window until you end the process with CTRL+C.

You can also open an additional command line window and type sencha fs web stop to stop the web server.

Point Architect to the URL Prefix of the Web Server

You can preview your project at any time. You can configure settings for previewing now or wait until you have added more to your app.

To preview your project, point Architect to the URL of where your project resides on your computer.

To set the URL prefix, click Settings in the Toolbar:

In the Settings window:

Edit the URL prefix field to point to the directory you created. The field should contain a URL that looks something like http://localhost/myprojects/sampleproject1 (replacing myprojects with the folder name you chose if it is something else). Do this carefully or you won't be able to save your project correctly or preview it in a browser. If you are using the Sencha Cmd web server, use the http://localhost:1841/directory_name URL. Other web servers may use a different port number after "localhost" or no port number.

You must edit the URL prefix for each new project to save and preview the project correctly.

Build Views to Define the UI

Construct the visual user interface for the City Bars application.

Click "Views" in the Toolbox to display a list of all the possible views.

In this section, we create a:

Main Navigation View

To configure Navigation View:

  1. In the Views Toolbox category, select Navigation View.
  2. Drag the Navigation View onto the Canvas.
  3. In Project Inspector > Config, set the following:
    userAlias: mainnav
    userClassName: MainNav
  4. Click the Save icon on the Toolbar to save your work.
    You should save your project frequently.

List View

To configure List View:

  1. Scroll the Toolbox up to the Containers section and drag Container to the Views item in Project Inspector. By dragging the Container to the Project Inspector instead of to the Canvas, the Container becomes a top-level component in the Views:

  2. Set the following Config values for the Container:
    userAlias: listcontainer
    userClassName: ListContainer
    layout: fit
  3. Scroll the Toolbox back to the Views category and drag a List view to the ListContainer in the Project Inspector.
  4. Set the following Config value for List:
    id: dataList
  5. Double-click the itemTpl item in Project Inspector. ("tpl" is an abbreviation for template.)
  6. Copy the following HTML code and paste it over the existing text and <div> tags in the Canvas Code view:
    <img class="photo" src="{photo_url}" width="40" height="40"/>{name}<br/>
    <img src="{rating_img_url_small}"/>&nbsp;<small>{address1}</small>
    
    For more information about the tpl configuration and templates, see the Ext.Template page.
  7. In the Project Inspector, drag the ListContainer onto the MainNav view.

    This creates a linked instance of the container to the MainNav view.
  8. Select the Link option from the Copy Component dialog box:

    The Project Inspector shows the container under MainNav as follows:

  9. Select the linked instance of the container listcontainer under MainNav and set the Config value:
    title: City Bars

Detail View

To configure details:

  1. In the Toolbox Filter field, type Tab to locate the Tab Panel container.

  2. Drag the Tab Panel to the Views item in the Project Inspector so that the Tab Panel is a top-level component:

  3. Set the following Config values:
    userAlias: detailpanel
    userClassName: DetailPanel
  4. Find the Tab Bar Config property in Config and add a tab bar under the tab panel (DetailPanel) by clicking the add button (+).
  5. Move the tab bar above the three tabs by right-clicking it in the Project Inspector and selecting Move Up three times:

  6. Set the following Config values for the Tab Bar:
    pack: center
    docked: top
    ui: light

Contact Tab

To configure contacts:

  1. Select Tab 1 in the Project Inspector. Note: This is a Container (Ext.Container).
  2. Set the following Config values:
    id: contact
    title: Contact
  3. In the Project Inspector, drag Tab 2 and Tab 3 into the contact container to make them children of contact. We are simply reusing containers that otherwise would be deleted and re-added. The Project Inspector for the DetailPanel should look like this:

  4. Select MyContainer1 in the Project Inspector and set the following Config values:
    id: info
    layout: hbox
    padding: 10
    tpl: - Click the plus (+) symbol to the right of the tpl Config item to add a template. Double-click the tpl item in the Project Inspector and add this code:
    <img class="photo" src="{photo_url}" width="100" height="100"/>;
    <h2>{name}</h2><div class="info">{address1}<br/>
    <img src="{rating_img_url_small}"/></div>
    
  5. Add a Component as a child of info. Find Component in the Toolbox and drag it onto the info item in the Project Inspector. Note: The Component is added as MyComponent in the Project Inspector.
  6. Set the following Config values:
    id: photo
    height: 100
    width: 100
    tpl: - Click the plus (+) symbol to the right of the tpl Config item to add a template. Double-click the tpl item in the Project Inspector and add this code:
    <img class="photo" src="{photo_url}" width="100" height="100"/>
  7. Add a second Component as a child of info and set the following Config values:
    id: data
    padding: 10
    tpl: - Click the plus (+) symbol to the right of the tpl Config item to add a template. Double-click the tpl item in the Project Inspector and add this code:
    <h2>{name}</h2><div class="info">{address1}<br/>
    <img src="{rating_img_url_small}"/></div>
  8. Select MyContainer2 under the contact Container and set the following Config values:
    layout: hbox
    pack: center
  9. Add a Button to MyContainer2, and set the button's Config values as follows:
    text: Call
    width: 100
  10. Add a Spacer to MyContainer2 and set the Spacer's Config value to:
    width: 57
  11. Add another Button to MyContainer2, and set the button's Config values to:
    text: More
    width: 100

In this tutorial, we set up the buttons, but do not assign functionality to them. You are invited to add functionality to the buttons; if you do, please share your results on the Architect forum.

Map Tab

To configure the map tab:

  1. Add a Map to the DetailPanel as a sibling to contact and set these Config values:
    id: detailMap
    title: Map
    height: Be sure this remains unset
  2. Save your project.

Build a Model and a Store to Define the Data

Now that we have defined views for the application, we need to provide some data to display in those views. The controller queries the Yelp database and creates a store, which in this case is a JSONP file that contains the relevant information. The model defines how this data is represented by your application.

The Model

First, we add a model to represent the data objects used in the application; think of it as sort of a schema definition for the data.

To add and configure a model:

  1. In the Project Inspector, click the plus (+) sign and click Model:

    The model appears as MyModel.
  2. Set this Config value for MyModel:
    userClassName: Business

    Note: You can create several of the fields at once by supplying a comma-separated list of fields rather than adding them individually. See Stores and Models for more information.
  3. Click the plus (+) sign for the fields Config item and add these fields to the model - you can copy the names here and paste them into the fields edit box:
    id, name, latitude, longitude, address1, address2, address3, phone, city, state_code, zip, mobile_url, rating_img_url_small, photo_url
    Individually, these fields are:
    1. id
    2. name
    3. latitude
    4. longitude
    5. address1
    6. address2
    7. address3
    8. phone
    9. city
    10. state_code
    11. zip
    12. mobile_url
    13. rating_img_url_small
    14. photo_url

Note: In this case, the model contains a number of fields that we are not using. You can extend this application later to use the fields we don't currently use.

For a simple application like this one, using a model rather than just directly accessing the data in the store may seem cumbersome but in real applications, the model supports the following and offers powerful ways to manage data within the application:

  • Associations: BelongsTo or HasMany
  • ID Generators: Sequential or UUID
  • Proxies: AJAX, Direct, REST, and so forth
  • Validations: Exclusion/Inclusion, Format, Length, and so forth

The Store

The Store is a file that serves as a client-side data cache for the UI components. In this case, we are using a JSONP store, which is similar to a JSON store, but it can retrieve JSON data from a domain other than the one in which your application is running.

For more detail, see the Touch API documentation for Ext.data.JsonP.

You can also create array stores, XML stores, and tree stores.

To configure a store:

  1. Click the Project Inspector (+) symbol and click Store > JsonP Store:

    The JsonP Store appears in Project Inspector as MyJsonPStore.
  2. Set the MyJsonPStore Config values as follows:
    userClassName: BusinessStore
    storeId: BusinessStore
    model: Business
    Note: The Store's model: Business value associates the Store with the Models > Business > userClassName value. Until you set the model value, the JsonP Store displays a red warning indicator:

    The Store model and Model userClassName values must be identical and they are case sensitive. One of the most common mistakes is having different names for these values.
  3. Select MyJsonReader in the Inspector and set its rootProperty Config to businesses.

Note A JsonP store is automatically configured with the Touch Ext.data.reader.Json and Ext.data.proxy.JsonP.

The Controller

A controller implements the actual functionality for the app; in this case, it queries the Yelp database for a list of bars with their locations and saves that information in the JSONP store that we defined in the previous The Store section.

Important You need to first register for a Yelp API key before you can complete the steps in this section. For more information, see Step 4 in the Preliminary Steps section earlier in this guide.

To add a controller:

  1. In the Project Inspector, click the plus (+) symbol and click Controller - The new Controller appears in the Project Inspector as MyController:

  2. Rename MyController to Business by setting its Config value:
    userClassName: Business
  3. On the Canvas, click Code:

  4. In the Project Inspector, click the plus (+) Add symbol for the Config launch value:

  5. Click the launch Select icon to add text:

  6. Insert the following code in the launch Code view to get the user's current location, use Yelp to get businesses, and display the list of bars:
        var me = this;
    
        Ext.Viewport.setMasked({ message: 'Loading...' });
        // Get the user's location
        me.getLocation(function (location) {
    
            // Use Yelp to get the business names
            me.getBusinesses(location, function (store) {
    
                // Bind data to the list and display it
                me.getDataList().setStore(store);
    
                Ext.Viewport.setMasked(false);
            });
        });
    
  7. Add four controller references:
    1. In the Project Inspector, click Business.
    2. In Config, find References.
    3. Click the plus (+) Add symbol for References to add the first controller reference.
    4. Type the name as dataList, click Next, type the Selector as #dataList and click Finish:

  8. Add three additional controller references using the same technique, as follows:
    1. Name the second reference listCard and set its selector to #listCard.
    2. Name the third reference mainNav and set its selector to mainnav.
    3. Name the fourth reference detailCard and set its selector to detailpanel. Note: The first two references use an ID to query -- #listCard -- and the last two use an alias -- mainnav.
  9. In Project Inspector with the Business controller selected, add a function:
    Locate Functions in Config and click the (+) icon.
    Set its Config values:
    Function: getLocation
    Parameters: callback
  10. Double-click the getLocation function in the Project Inspector, and insert the following code into the code editor:
        if (navigator && navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                callback(position);
            }, function(error) {
                // Handle the error
            });
        }
    
  11. Add another function and set the Config values--double-click Business to return the Config values to where they can be set:
    Function: getBusinesses
    Parameters: location, callback
  12. Double-click the getBusinesses function in the Inspector, and insert the following code into the code editor. This code obtains data for your app from Yelp - Insert your Yelp API key in the yelpKey = '' statement in this code:
        // Note: Obtain a Yelp API key by registering (for free) 
        // with Yelp at http://www.yelp.com/developers/getting_started/api_overview
        // (in this app, we use the Review Search API v1.0)
        var store = Ext.data.StoreManager.lookup('BusinessStore'),
            yelpKey = '', // Enter your Yelp API key here
            url = 'http://api.yelp.com/business_review_search' +
            '?ywsid=' + yelpKey +
            '&term=Bars' +
            '&lat=' + location.coords.latitude +
            '&long=' + location.coords.longitude;
        store.getProxy().setUrl(url);
        store.load(function() {
            callback(store);
        });
      
    Note If you don't have a Yelp API key, register (for free) with Yelp.
  13. Add an Action to the controller to display the DetailPanel when the user taps an item in the main list.
    In the Project Inspector, click the Business controller.
    In Config, click the Actions (+) symbol, and click Controller Action:

  14. In Config for the Controller Action, choose from the drop-down lists:
    Target type: Ext.dataview.List
    Event by name: itemtap
  15. In Config, click the arrow to the right of the itemTap Action, or in the Project Inspector, double-click the itemtap onListItemTap Action, and enter these Config values:
    controlQuery: #dataList
    fn: onListItemTap
  16. In Project Inspector, double-click the itemtap onListItemTap Action to open the code editor and add the following code:
        var map,
            info,
            details;
    
        if (record) {
            details = Ext.create('CityBars.view.DetailPanel', {
                title: 'Details'
            });
    
            // stash info for later use by the map card
            map = details.child('#detailMap');
            map._record = record;
    
            // set the info
            info = details.child('#contact').child('#info');
            info.child('#photo').setData(record.data);
            info.child('#data').setData(record.data);
    
            this.getMainNav().push(details);
        }
        
  17. Add another Controller Action to the Business Controller to center the map on the correct location when a user touches the Map tab.
    In Config, click the (+) icon for Actions, and click Controller Action:

  18. In Config, select these values from the drop-down menus:
    Target type: Ext.Map
    Event by name: activate
  19. Click the activate action's arrow, or in Project Inspector, double-click the activate action, and set these Config values:
    controlQuery: detailpanel > map
    fn: onMapActivate
  20. In Project Inspector, double-click the activate onMapActivate action to open the code editor and add the following code:
        var map = newActiveItem,
           record = map._record,
           lat = record.get('latitude'),
           lng = record.get('longitude'),
           centerMap = Ext.Function.createDelayed(function() {
               map.setMapOptions({
                   zoom: 18
               });
               map.setMapCenter({
                   latitude: lat,
                   longitude: lng
               });
           }, 250),
           geocoder, loc;
    
        if (lat && lng) {
           centerMap();
        } else {
           geocoder = this._geocoder || (this._geocoder = new google.maps.Geocoder());
           geocoder.geocode(
               {address: [
                   record.get('address1'),
                   record.get('address2'),
                   record.get('address3'),
                   record.get('city'),
                   record.get('state_code'),
                   record.get('zip')
               ].join(', ')},
               function(results, status) {
                   if (status == google.maps.GeocoderStatus.OK) {
                       loc = results[0].geometry.location;
                       lat = loc.lat();
                       lng = loc.lng();
                       record.set('latitude', lat);
                       record.set('longitude', lng);
                       centerMap();
                   } else {
                       Ext.Msg.alert("Could not find location: " + status);
                   }
               }
           );
        }
       

An important concept to grasp is that the view never calls the controller to invoke methods. Instead, the view generates an event and the controller responds to that event. After you build a view, you associate it with a controller by using a controller action that is set using the Config panel.

For more information, see Controllers.

Add a Style Sheet

To improve the look of the app, giving it an attractive theme, you need to add a style sheet.

To add a style sheet:

  1. In the Project Inspector, click the add button (+) and choose Resource > CSS Resource. The Resources node displays a new CSS resource:

  2. Select it there and set its url cConfig to citybars.css.
  3. Download and unzip the citybars.css.
  4. Place the citybars.css file in the citybars folder you set up at the beginning of the project to store your app. Optionally, you can create a styles directory within the folder and set the url config to styles/styles.css.

Have a Look at Your Hard Work

View the application in the Inspector and be sure it now has the following:


Models: Business
Store: BusinessStore
Views: MainNav, ListContainer, DetailPanel

Save your project.

If you have not done so already, Point Architect to the URL of your web server, and open the app.html file for your project.

Here's what it should look like.

You can also deploy the project to a hosted location and view it there. You can then navigate using your browser to view the application. Chrome should work fine, or view it through a WebKit browser on a mobile device.

What if it Doesn't Work?

If the app does not work, check the following:

  1. Ensure you are using Chrome or Safari, or if working from a mobile device, Chrome, Safari, or Windows Explorer 10 or later.
  2. Be sure that you have your own Yelp API key and code it into the Controller of your application.
  3. Check for typos in the userAlias and userClassName configurations for the views you defined and the code that calls them.
  4. Check that the item IDs are set correctly.
  5. Architect protects you against many common typos you can make in JavaScript such as missing semicolons but look carefully at what you typed.

You can also download the completed project from the City Bars code site at https://github.com/SenchaArchitect/CityBars and see where your code differs to find the problem.

Additional Steps

Additional steps are required to build and package your application for production. See Publishing, Packaging, and Simulating a Project for more information.