Using DataViews in Sencha Touch

DataView makes it easy to create dynamically a number of components, usually based off a store. It is used for rendering data from your server back-end or any other data source, and it powers components such as list.

You can use dataView whenever you want to show repeatedly sets of the same component, for example in cases such as the following:

  • A list of messages in an email app
  • A list of the latest news or tweets
  • A tiled set of albums in an HTML5 music player

Creating a Simple DataView

At its simplest, a dataView is a store full of data and a template that is used to render each store item, as illustrated by the following example:

Editor Preview Open in Fiddle
Ext.application({
    name: 'Sencha',

    launch: function() {

        var touchTeam = Ext.create('Ext.DataView', {
            fullscreen: true,

            store: {
                fields: ['name', 'age'],
                data: [
                    {name: 'Greg',  age: 100},
                    {name: 'Brandon',   age: 21},
                    {name: 'Scott',   age: 21},
                    {name: 'Gary', age: 24},
                    {name: 'Fred', age: 24},
                    {name: 'Seth',   age: 26},
                    {name: 'Kevin',   age: 26},
                    {name: 'Israel',   age: 26},
                    {name: 'Mitch', age: 26}
                ]
            },

            itemTpl: '{name} is {age} years old'
        });
    }
});

In this example we defined the store inline, so all data is local and therefore does not have to be loaded from a server. For each of the data items defined in the store, dataView renders a div and passes in the name and age data. The div uses the specified itemTpl and renders the data inside the curly bracket placeholders.

Because dataView is integrated with store, any changes to the store are immediately reflected on the screen. For example, if we added a new record to the store, it would be rendered into our dataView:

touchTeam.getStore().add({
    name: 'Liz Lemmons',
    age: 33
});

After adding the new record as shown in the previous code sample, we do not have to manually update the dataView, since it is automatically updated. The same would happen if we modified one of the existing records in the store:

touchTeam.getStore().getAt(0).set('age', 42);

This will get the first record in the store and change age to 42 and automatically update the screen content.

Loading Data from a Server

We often want to load data from our server or some other web service, so that we do not have to hard-code the data content locally. Let us say we wanted to load the latest Sencha forum threads into a dataView, and for each thread render the thread title. To do this we need to modify the dataView store and itemTpl as follows:

Editor Preview Open in Fiddle
Ext.application({
    name : 'Fiddle',

    launch : function() {

        var store = Ext.create('Ext.data.Store', {
            autoLoad: true,
            fields: ['title'],
            proxy: {
                type: 'jsonp',
                url: 'https://www.sencha.com/forum/remote_topics/index.php',
                reader: {
                    rootProperty: 'topics',
                    totalProperty: 'totalCount'
                }
            }            
        });

        Ext.create('Ext.DataView', {
            fullscreen: true,
            store: store,
            itemTpl: '

{title}

' }); } });

In this example, the dataView no longer contains data items, instead we have provided a proxy, which fetches the data. In this case we used a JSON-P proxy that loads data using Sencha’s JSON-P forum results. We also specified the title for each thread, and used Store’s autoLoad configuration to load the data automatically. Finally, we configured a Reader to decode the response from Sencha.com, indicating it to expect JSON and that the threads are found in the ‘topics’ part of the JSON response.

Styling a DataView

You may have realized by now that although our dataView is displaying data from our store, it does not have any default styling. The lack of default styling is by design, but adding custom CSS is very simple. dataView has two configurations that support targeting your custom CSS to the view: baseCls and itemCls. baseCls is used to add a className around the outer element of the dataView. The itemCls you provide is added onto each item that is rendered into our dataView.

If you do not specify an itemCls, it automatically takes the baseCls configuration (which defaults to x-dataview) and prepends -item to it. As a result, each item will have a className of x-dataview-item.

Before adding the configuration, we need to create the custom CSS shown in the following example:

.my-dataview-item {
    background: #ddd;
    padding: 1em;
    border-bottom: 1px solid #ccc;
}
.my-dataview-item img {
    float: left;
    margin-right: 1em;
}
.my-dataview-item h2 {
    font-weight: bold;
}

Once the CSS is complete, we can go back to our previous JSONP example and add the baseCls configuration:

Ext.create('Ext.DataView', {
    fullscreen: true,
    store: store,
    itemTpl: '<p>{title}</p>',
    baseCls: 'my-dataview',
    //As described above, we don't need to set itemCls in most 
    //cases as it will already add a className
    //generated from the baseCls to each item.
    //itemCls: 'my-dataview-item'                
});

Component DataView

In the previous example we created a dataView with an itemTpl, which means each item is rendered as a basic div from a XTemplate. However, sometimes you need each item to be a component, so you can provide a rich UI for users. In Sencha Touch, we introduced the useComponents configuration which allows you to address this scenario.

Creating a component dataView is very similar to creating a normal template-based dataView as previously shown, however you must define the item view used when rendering each item in your list. Each of the store’s records will translate into a dataItem, which extends from a container, so you can have multiple components inside of it. In this example we’re using a custom updateRecord method implementation that updates our DataItems’ Components based on the data values:

Editor Preview Open in Fiddle
Ext.application({
    name: 'Sencha',

    launch: function() {   

        Ext.define('TestModel', {
            extend: 'Ext.data.Model',
            config: {
                fields: [{
                    name: 'val1'
                }, {
                    name: 'val2'
                }]
            }
        });

        Ext.define('TestStore', {
            extend: 'Ext.data.Store',
            config: {
                data: [{
                    val1: 'A Button',
                    val2: 'with text'
                }, {
                    val1: 'The Button',
                    val2: 'more text'
                }, {
                    val1: 'My Button',
                    val2: 'My Text'
                }],
                model: 'TestModel',
                storeId: 'TestStore'
            }
        });

        Ext.define('MyDataItem', {
            extend: 'Ext.dataview.component.DataItem',
            alias: 'widget.mydataitem',
            config: {
                padding: 10,
                layout: {
                    type: 'hbox'
                },
                defaults: {
                    margin: 5
                },
                items: [{
                    xtype: 'button',
                    text: 'Val1'
                }, {
                    xtype: 'component',
                    flex: 1,
                    html: 'val2',
                    itemId: 'textCmp'
                }]
            },
            updateRecord: function(record) {
                var me = this;

                me.down('button').setText(record.get('val1'));
                me.down('#textCmp').setHtml(record.get('val2'));

                me.callParent(arguments);
            }
        });

        Ext.define('MyDataView', {
            extend: 'Ext.dataview.DataView',
            config: {
                defaultType: 'mydataitem',
                useComponents: true
            }
        });

        Ext.create('MyDataView', {
            fullscreen: true,
            store: Ext.create('TestStore')
        });
    }
});

Another more advanced example, using a datamap:

Ext.define('MyListItem', {
    extend: 'Ext.dataview.component.DataItem',
    requires: ['Ext.Button'],
    xtype: 'mylistitem',

    config: {
        nameButton: true,

        dataMap: {
            getNameButton: {
                setText: 'name'
            }
        }
    },

    applyNameButton: function(config) {
        return Ext.factory(config, Ext.Button, this.getNameButton());
    },

    updateNameButton: function(newNameButton, oldNameButton) {
        if (oldNameButton) {
            this.remove(oldNameButton);
        }

        if (newNameButton) {
            this.add(newNameButton);
        }
    }
});

This example shows how to define a component-based dataView item component. There are a few important notes about this example:

  • We must extend dataItem for each item. This is an abstract class which handles the record handling for each item.

  • Following the extend code we require Ext.Button inside the item component.

  • We specify the xtype for this item component.

  • Inside the config block we define the nameButton item. This custom configuration added to the component will be transformed into a button by the class system. By default we set it to true , but this could also be a configuration block. This configuration automatically generates getters and setters for the nameButton item.

  • We define the datamap. The dataMap is a map between the data of a model and this view. The getNameButton is the getter for the instance you want to update; so in this case we want to get the nameButton configuration of this component. Inside that block we then give it the setter for that instance, setText in this case and give it the field of the record we are passing. As a result, once this item component gets a record, it gets the nameButton and then calls setText with the name value of the record.

  • Finally we define the apply method for the nameButton item. The apply method uses factory. That instance is then returned, which then causes updateNameButton to be called. The updateNameButton method removes the old nameButton instance if it exists, and adds the new nameButton instance.

After having created the item component, we can create the component dataview, similar to previous examples.

Ext.create('Ext.DataView', {
    fullscreen: true,

    store: {
        fields: ['name', 'age'],
        data: [
            {name: 'Greg',  age: 100},
            {name: 'Brandon',   age: 21},
            {name: 'Scott',   age: 21},
            {name: 'Gary', age: 24},
            {name: 'Fred', age: 24},
            {name: 'Seth',   age: 26},
            {name: 'Kevin',   age: 26},
            {name: 'Israel',   age: 26},
            {name: 'Mitch', age: 26}
        ]
    },

    useComponents: true,
    defaultType: 'mylistitem'
});

This code has two key additions. First, we added the useComponents configuration and set it to true. Second, we set the defaultType configuration to the previously created mylistitem item component. This tells the dataview to use the defined item component as the view for each item.

If we run this code together, we can see the component dataview in action.

Editor Preview Open in Fiddle
Ext.application({
    name: 'Sencha',

    launch: function() {    
        Ext.define('MyListItem', {
            extend: 'Ext.dataview.component.DataItem',
            requires: ['Ext.Button'],
            xtype: 'mylistitem',

            config: {
                nameButton: true,

                dataMap: {
                    getNameButton: {
                        setText: 'name'
                    }
                }
            },

            applyNameButton: function(config) {
                return Ext.factory(config, Ext.Button, this.getNameButton());
            },

            updateNameButton: function(newNameButton, oldNameButton) {
                if (oldNameButton) {
                    this.remove(oldNameButton);
                }

                if (newNameButton) {
                    this.add(newNameButton);
                }
            }
        });

        Ext.create('Ext.DataView', {
            fullscreen: true,

            store: {
                fields: ['name', 'age'],
                data: [
                    {name: 'Greg',  age: 100},
                    {name: 'Brandon',   age: 21},
                    {name: 'Scott',   age: 21},
                    {name: 'Gary', age: 24},
                    {name: 'Fred', age: 24},
                    {name: 'Seth',   age: 26},
                    {name: 'Kevin',   age: 26},
                    {name: 'Israel',   age: 26},
                    {name: 'Mitch', age: 26}
                ]
            },

            useComponents: true,
            defaultType: 'mylistitem'
        });
    }
});

The great benefit of this approach is the flexibility it adds to your dataviews. Since each item component has access to its own Ext.dataview.component.DataItem#record, you can do just about anything with it.

In the following example we add to the nameButton an event listener to the tap event, which alerts the user with the age of the selected person.

Ext.define('MyListItem', {
    //...

    updateNameButton: function(newNameButton, oldNameButton) {
        if (oldNameButton) {
            this.remove(oldNameButton);
        }

        if (newNameButton) {
            // add an event listeners for the `tap` event onto the new button, and
            // tell it to call the onNameButtonTap method
            // when it happens
            newNameButton.on('tap', this.onNameButtonTap, this);

            this.add(newNameButton);
        }
    },

    onNameButtonTap: function(button, e) {
        var record = this.getRecord();

        Ext.Msg.alert(
            record.get('name'), // the title of the alert
            "The age of this person is: " + record.get('age') 
            // the message of the alert
        );
    }
});

Finally, after adding this code to our previous example, we get the following finished result:

Editor Preview Open in Fiddle
Ext.application({
    name: 'Sencha',

    launch: function() {

        Ext.define('MyListItem', {
            extend: 'Ext.dataview.component.DataItem',
            requires: ['Ext.Button'],
            xtype: 'mylistitem',

            config: {
                nameButton: true,

                dataMap: {
                    getNameButton: {
                        setText: 'name'
                    }
                }
            },

            applyNameButton: function(config) {
                return Ext.factory(config, Ext.Button, this.getNameButton());
            },

            updateNameButton: function(newNameButton, oldNameButton) {
                if (oldNameButton) {
                    this.remove(oldNameButton);
                }

                if (newNameButton) {
                    // add an event listeners for the `tap` event onto the new button, and
                    // tell it to call the onNameButtonTap method
                    // when it happens
                    newNameButton.on('tap', this.onNameButtonTap, this);

                    this.add(newNameButton);
                }
            },

            onNameButtonTap: function(button, e) {
                var record = this.getRecord();

                Ext.Msg.alert(
                    record.get('name'), // the title of the alert
                    "The age of this person is: " + record.get('age') 
                    // the message of the alert
                );
            }
        });

        Ext.create('Ext.DataView', {
            fullscreen: true,

            store: {
                fields: ['name', 'age'],
                data: [
                    {name: 'Greg',  age: 100},
                    {name: 'Brandon',   age: 21},
                    {name: 'Scott',   age: 21},
                    {name: 'Gary', age: 24},
                    {name: 'Fred', age: 24},
                    {name: 'Seth',   age: 26},
                    {name: 'Kevin',   age: 26},
                    {name: 'Israel',   age: 26},
                    {name: 'Mitch', age: 26}
                ]
            },

            useComponents: true,
            defaultType: 'mylistitem'
        });
    }
});
Last updated