How to Create a Sencha Touch 2 App, Part 2

In this second part of the tutorial on how to build a Sencha Touch 2 application we will continue building a small application that allows people to save notes on the device running the app.

So far, we have been working on the View that renders the list of notes cached on the device:

While building this View, we defined the NotesListContainer Class. We are going to start this article with a modification to this Class. This modification will promote encapsulation, and make the app easier to change and maintain.

We had previously defined the NotesListContainer Class as follows:

Ext.define("NotesApp.view.NotesListContainer", {
    extend: "Ext.Container",
    config: {
        items: [{
            xtype: "toolbar",
            docked: "top",
            title: "My Notes",
            items: [{
                xtype: "spacer"
            }, {
                xtype: "button",
                text: "New",
                ui: "action",
                id:"new-note-btn"
            }]
        }]
    }
});

The changes we will make to this View consist of using the Class’s initialize() function to define its components. We will begin creating a new Class definition like so:

Ext.define("NotesApp.view.NotesListContainer", {
    extend: "Ext.Container",
    alias: "widget.noteslistcontainer",

    initialize: function () {

        this.callParent(arguments);

    }
});

Notice how we are using the alias config. This config is very helpful, as it effectively defines an xtype for our Class. Thanks to the alias, we can now refer to the NotesListContainer Class with the xtype=”noteslistcontainer” config. We will use this construct to instantiate the Class later in the article,

In Sencha Touch 2, every Class has an initialize() function. Initialize() can be used to perform logic right after the Class is instantiated, it replaces the initComponent() function that exists in Sencha Touch 1, and we can use it to add the toolbar with the New button:

Ext.define("NotesApp.view.NotesListContainer", {
    extend: "Ext.Container",
    alias: "widget.noteslistcontainer",

    initialize: function () {

        this.callParent(arguments);

        var newButton = {
            xtype: "button",
            text: 'New',
            ui: 'action',
            handler: this.onNewButtonTap,
            scope: this
        };

        var topToolbar = {
            xtype: "toolbar",
            title: 'My Notes',
            docked: "top",
            items: [
                { xtype: 'spacer' },
                newButton
            ]
        };

        this.add([topToolbar]);
    },
    onNewButtonTap: function () {
        console.log("newNoteCommand");
        this.fireEvent("newNoteCommand", this);
    },
    config: {
        layout: {
            type: 'fit'
        }
    }
});

In the initialize() function, after invoking callParent(), we define the New button variable, along with the Toolbar. As you already know from the previous chapter, the Toolbar’s items are the spacer and the Button.

Our last step within initialize() consists of adding the Toolbar to the View’s items via a call to the add() function.

If you go back to the newButton definition, you will notice that we’ve added a tap handler using the handler config:

var newButton = {
    xtype: "button",
    text: 'New',
    ui: 'action',
    handler: this.onNewButtonTap,
    scope: this
};

This function will capture tap events on the button, and transform them into an event that is more specific and descriptive of the application’s business logic. We will call this event newNoteCommand. Here’s the handler’s implementation:

onNewButtonTap: function () {
    console.log("newNoteCommand");
    this.fireEvent("newNoteCommand", this);
}

This is one of the important changes we are making to the NotesListContainer Class. In the first article of the series, the tap event on the button was captured by the Controller:

Ext.define("NotesApp.controller.Notes", {
    extend: "Ext.app.Controller",
    config: {
        refs: {
            newNoteBtn: "#new-note-btn"
        },
        control: {
            newNoteBtn: {
                tap: "onNewNote"
            }
        }
    },
    onNewNote: function () {
        console.log("onNewNote");
    }

    // Rest of the controller's code omitted for brevity.
});

Now, we’re capturing the event within the View, and broadcasting a new event, newNoteCommand, which will be captured by the Controller:

onNewButtonTap: function () {
    console.log("newNoteCommand");
    this.fireEvent("newNoteCommand", this);
}

Although both approaches are valid, there are important benefits derived from the second approach:

  • The View’s interface is cleaner. It now fires events that are more in line with the business logic of the application.
  • The View is easier to modify and maintain, as the Controller does not need intimate knowledge of the View’s inner workings.

As long as the View’s public events remain the same, the Controller will be able to work with the View. For example, we can change the elements used to trigger the creation of a new note in the View without affecting the Controller. The Controller only needs to listen to the newNoteCommand event fired from the view.

The next step of this refactoring will take place in the app.js file, where we will modify the application() function so we create our NoteListContainer instance using the Class’s alias:

Ext.application({
    name: "NotesApp",

    controllers: ["Notes"],
    views: ["NotesListContainer"],

    launch: function () {

        var notesListContainer = {
            xtype: "noteslistcontainer"
        };

        Ext.Viewport.add(notesListContainer);
    }
});

And finally, we will switch over to the controller and modify the refs section just so we lookup our ref by xtype instead of by id:

Ext.define("NotesApp.controller.Notes", {

    extend: "Ext.app.Controller",
    config: {
        refs: {
            // We're going to lookup our views by xtype.
            notesListContainer: "noteslistcontainer"
        },
        control: {
            notesListContainer: {
                // The commands fired by the notes list container.
                newNoteCommand: "onNewNoteCommand",
                editNoteCommand: "onEditNoteCommand"
            }
        }
    },

    // Commands.
    onNewNoteCommand: function () {

        console.log("onNewNoteCommand");
    },
    onEditNoteCommand: function (list, record) {

        console.log("onEditNoteCommand");
    },
    // Base Class functions.
    launch: function () {
        this.callParent(arguments);
        console.log("launch");
    },
    init: function () {
        this.callParent(arguments);
        console.log("init");
    }
});

Notice that we also added the onEditNoteCommand event and editNoteCommand handler to the controller. We will define the onEditNoteCommand in the next section of the tutorial, when we create the Notes List View.

After these changes, we can open the index.html page in our favorite WebKit browser, to confirm that everything is working as expected. Tapping the New button should produce the console message we added to the onNewButtonTap function:

Creating The Notes List View

The Notes List View is the component that will render the cached notes. Its file is NotesList.js, which we will place in the view folder. To create this component, we will extend the Sencha Touch’s Ext.dataview.List Class:

Ext.define("NotesApp.view.NotesList", {
    extend: "Ext.dataview.List",
    alias: "widget.noteslist",
    config: {
        loadingText: "Loading Notes...",
        emptyText: '</pre>
<div class="notes-list-empty-text">No notes found.</div>
<pre>',
        onItemDisclosure: true,
        itemTpl: '</pre>
<div class="list-item-title">{title}</div>
<div class="list-item-narrative">{narrative}</div>
<pre>',
    }
});

In this definition, we are setting the onItemDisclosure config to true, which means that we want the list to display a disclosure button next to each item:

A tap on the disclosure button will trigger the Note editing feature of the application. We will create the disclosure handler function in a few minutes.

In the NotesList Class, pay attention to the different CSS classes we use in the itemTpl and emptyText configs. They will allow us to nicely format both the list items, and the message the list will show when there are no items to display.

Before creating these styles we need to create the app.css file. We will place the file in the resources/css directory:

Here are the styles we need:

/* Increase height of list item so title and narrative lines fit */
.x-list .x-list-item .x-list-item-label
{
     min-height: 3.5em!important;
}
/* Move up the disclosure button to account for the list item height increase */
.x-list .x-list-disclosure {
position: absolute;
bottom: 0.85em;
right: 0.44em;
}
.list-item-title
{
    float:left;
    width:100%;
    font-size:90%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right:25px;
    line-height:150%;
}
.list-item-narrative
{
    float:left;
    width:95%;
    color:#666666;
    font-size:80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right:25px;
}
.x-item-selected .list-item-title
{
    color:#ffffff;
}
.x-item-selected .list-item-narrative
{
    color:#ffffff;
}
.notes-list-empty-text
{
    padding:10px;
}

In order to render the NotesList instance, we first need to add the Class name to the views config of the application:

views: ["NotesList", "NotesListContainer"]

Then, we need to add it to the NotesListContainer Class. Back in the NotesListContainer.js file, we will add the notesList variable to the initialize() function:

Ext.define("NotesApp.view.NotesListContainer", {
    extend: "Ext.Container",
    alias: "widget.noteslistcontainer",

    initialize: function () {

        this.callParent(arguments);

        var newButton = {
            xtype: "button",
            text: 'New',
            ui: 'action',
            handler: this.onNewButtonTap,
            scope: this
        };

        var topToolbar = {
            xtype: "toolbar",
            title: 'My Notes',
            docked: "top",
            items: [
                { xtype: 'spacer' },
                newButton
            ]
        };

        var notesList = {
            xtype: "noteslist",
            listeners: {
                disclose: { fn: this.onNotesListDisclose, scope: this }
            }
        };

        this.add([topToolbar, notesList]);
    },
    onNewButtonTap: function () {
        console.log("newNoteCommand");
        this.fireEvent("newNoteCommand", this);
    },
    config: {
        layout: {
            type: 'fit'
        }
    }
});

Notice how we are setting a listener for the disclose event of the list:

var notesList = {
    xtype: "noteslist",
    listeners: {
        disclose: { fn: this.onNotesListDisclose, scope: this }
    }
};

Now we can define the onNotesListDisclose() function as follows:

onNotesListDisclose: function (list, record, target, index, evt, options) {
    console.log("editNoteCommand");
    this.fireEvent('editNoteCommand', this, record);
}

Here we are taking the approach we followed earlier with the New button. Instead of having the Controller listen to the disclose event of the List, we are hiding this event, and creating the editNoteCommand event, which we will expose to the Controller. This is another step towards making the application more flexible and easier to maintain.

Creating a Sencha Touch Data Model To Represent a Note

The Notes List requires a data store, which will supply the information for its list items. In order to create this store, we first need to define a data model that will represent a note.

Let’s go ahead and define the Note Class. We will place this Class in the Note.js file, which we will save in the model directory:

A note will have four fields: id, date created, title and narrative. We will start with the following definition:

Ext.define("NotesApp.model.Note", {
    extend: "Ext.data.Model",
    config: {
        idProperty: 'id',
        fields: [
            { name: 'id', type: 'int' },
            { name: 'dateCreated', type: 'date', dateFormat: 'c' },
            { name: 'title', type: 'string' },
            { name: 'narrative', type: 'string' }
        ]
    }
});

We will use the idProperty config to establish that the id field is actually the field the framework can use to uniquely identify a note. This seems trivial in our case because we have total control over the names of the fields of the data model. However, you might encounter cases where, for example, the data model’s fields are tightly coupled to column names in an existing database, and the name of the column that uniquely identifies a record is not “id”. This is why the idProperty config is important.

Setting Up Model Validation In Sencha Touch

The id, dateCreated and title fields in our Note Model are mandatory. We will express this requirement using the validations config:

Ext.define("NotesApp.model.Note", {
    extend: "Ext.data.Model",
    config: {
        idProperty: 'id',
        fields: [
            { name: 'id', type: 'int' },
            { name: 'dateCreated', type: 'date', dateFormat: 'c' },
            { name: 'title', type: 'string' },
            { name: 'narrative', type: 'string' }
        ],
        validations: [
            { type: 'presence', field: 'id' },
            { type: 'presence', field: 'dateCreated' },
            { type: 'presence', field: 'title', message: 'Please enter a title for this note.' }
        ]
    }
});

For the title field, we are taking advantage of the message config to define the message the user will see when she tries to save a note without typing in its title.

Before moving on to create the data store, we need to add the model to the models config of the application:

Ext.application({
    name: "NotesApp",

    models: ["Note"],

	// Rest of the app's definition omitted for brevity...
});

Creating a Sencha Touch Data Store

This is all we need for our data model at this point. Now we can focus on creating the data store that will feed the List. The Notes store goes in a new file. We will place this file in the store directory:

For now, the store will simply contain a few hard-coded records:

Ext.define("NotesApp.store.Notes", {
    extend: "Ext.data.Store",
    config: {
        model: "NotesApp.model.Note",
        data: [
            { title: "Note 1", narrative: "narrative 1" },
            { title: "Note 2", narrative: "narrative 2" },
            { title: "Note 3", narrative: "narrative 3" },
            { title: "Note 4", narrative: "narrative 4" },
            { title: "Note 5", narrative: "narrative 5" },
            { title: "Note 6", narrative: "narrative 6" }
        ]
    }
});

Worth highlighting here is the model config, which we use to establish that this store will contain instances of the Note model.

We want the Notes List to render the notes sorted by creation date. This is why we will add the sorters config to the store’s definition:

Ext.define("NotesApp.store.Notes", {
    extend: "Ext.data.Store",
    requires: "Ext.data.proxy.LocalStorage",
    config: {
        model: "NotesApp.model.Note",
        data: [
            { title: "Note 1", narrative: "narrative 1" },
            { title: "Note 2", narrative: "narrative 2" },
            { title: "Note 3", narrative: "narrative 3" },
            { title: "Note 4", narrative: "narrative 4" },
            { title: "Note 5", narrative: "narrative 5" },
            { title: "Note 6", narrative: "narrative 6" }
        ],
        sorters: [{ property: 'dateCreated', direction: 'DESC'}]
    }
});

Now we can jump back to the NotesListContainer.js file, and add the store to the notesList declaration in the NotesListContainer Class:

var notesList = {
    xtype: "noteslist",
    store: Ext.getStore("Notes"),
    listeners: {
        disclose: { fn: this.onNotesListDisclose, scope: this }
    }
};

Before we check how we are doing, let’s quickly switch over to the Controller’s definition in the controller/Notes.js file, locate the launch() function, and invoke the store’s load() function as follows:

launch: function () {
    this.callParent(arguments);
    Ext.getStore("Notes").load();
    console.log("launch");
}

We really don’t need this call now – remember that the data is hard-coded – but we are adding in preparation for the next chapter of the tutorial, where we will discontinue the use of hard-coded data, and begin using data stored in the browser’s cache.

What we need to do, though, is add a reference to the store in the app.js file:

Ext.application({
    name: "NotesApp",

    models: ["Note"],
    stores: ["Notes"],
    controllers: ["Notes"],
    views: ["NotesList", "NotesListContainer"],

    launch: function () {

        var notesListContainer = {
            xtype: "noteslistcontainer"
        };       

        Ext.Viewport.add(notesListContainer);
    }
});

Excellent! At this point we should be able to see the hard-coded notes rendered on the screen. Let’s start our emulator, where we should see something like this:

Summary

We began this article making a modification to the main View of the application. One change consisted of adding an initialize() function to the NotesListContainer Class, and using this function to instantiate the Toolbar and Notes List.

The second and more important change is the introduction of two new events, newNoteCommand and editNoteCommand, which will be fired by this View when our users need to create or edit a note. This change increases the maintainability and reliability of the View, and the application in general.

After modifying the NotesListContainer Class, we proceeded to create the NotesList Class. Inheriting from the Ext.dataview.List Class, this is the component that we will use to render the cached notes. This Class needs a data store to keep a cache of the existing notes, therefore we created the Notes store, along with the Note data model, which represents a note.

In the next chapter of this tutorial we will start working on the View that our users will utilize to edit and delete notes. While working on this View, we will become familiar with Sencha Touch forms, model validation, and client side caching using local storage.

Stay tuned!

Downloads

Download the source code for this article: NotesApp-ST2-Part2.zip

The Entire Series

Want To Learn More?

My Sencha Touch books will teach you how to create an application from scratch.

Comments

  1. Royo says

    Hi Jorge, Thanks for the awesome tutorial. I came across this after realizing that the Sencha tutorials are pathetic.

    After implementing the code above, the final rendered application doesn’t look the same as the screenshot you have shared. Its almost there in that the themes and colours are the same. But the text is different and off-center. Also, the disclosure buttons look odd. The arrows are not in the centre of the blue circle. I tried fiddling with the app.css to try and increase the size of each list item. But nothing happened. And I couldn’t figure out how to modify the arrows position in the blue circle. Any reason why this would happen? Have I missed out some key Sencha files?

    • says

      See if you are using the same ST version I am using. I’ve had similar problems when I inadvertently forgot to update some of the files to the right version.

  2. Shashi says

    Hi,

    I’m new to Sencha touch. I am trying out some examples using list, but facing problems: On adding the listeners config below, the view is stopped from rendering. If I remove the listeners function, the list is rendered correctly.
    So, it appears due to the addition of the listeners – could someone guide me as the right way to capture the select event.

    code:

    Ext.define(‘MyApp1.view.List1′, {
    extend: ‘Ext.Container’,
    config: {
    layout: {
    type: ‘vbox’
    },
    items: [
    {
    xtype: 'toolbar',
    docked: 'top',
    title: 'Toolbar'
    },
    {
    xtype: 'container',
    flex: 1,
    layout: {
    type: 'vbox'
    },
    items: [
    {
    xtype: 'list',
    flex: 1,
    store: {
    fields: ['title'],
    data: [
    { title: 'Item 1' },
    { title: 'Item 2' },
    { title: 'Item 3' },
    { title: 'Item 4' }
    ]
    },
    itemTpl: ‘{title}’,
    listeners: {
    select: function(view, record, eOpts) {
    Ext.Msg.alert(‘Selected!’, ‘You selected ‘ + record.get(‘title’));
    }
    }
    ]

    }
    ] //items – config
    } //config
    });

  3. says

    Jorge,
    Buenisimo! Excellent tutorial!
    I’ve been following your tutorial from the first one and cannot wait to complete them all.
    I’m curious, your website is called MiamiCoder — do you currently reside in Miami, FL?
    I also live there. I just wanted to know if you had any SenchaTouch/Mobile meetups so that I could go and get to know more devs and learn more.

    Thanks again!
    Camilo.

  4. Ankit says

    Hi,
    My question is bit off topic, but if you could answer it that would be great help.
    I want to use a grid component but Sencha touch 2 doesn’t have any inbuilt grid component in it.
    What are the options do i have ?
    I saw that there is a grid component available in Github, but how can i use it in my project.
    I am using Sencha Architect 2 and i don’t see any direct way to add an external component in it.

Leave a Reply

Your email address will not be published. Required fields are marked *