Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Sencha Touch 2 Stores: Client-Side Sorting

DZone's Guide to

Sencha Touch 2 Stores: Client-Side Sorting

· Java Zone
Free Resource

Never build auth again! The Okta Developer Platform makes it simple to implement authentication, authorization, MFA and more in Java applications. Get started with the free API.

This is a Sencha Touch Store sort tutorial where you will learn the different ways to perform client-side sorting of the records in a Sencha Touch Store. These are the topics that the tutorial covers:

  • Using a Sencha Touch Store’s sorters config
  • Using the Store Class’s sort method
  • Using the Store Class’s setSorters method

Let’s start by creating a small Sencha Touch app that we can use as a test bed. The app will have the following directories:

Sencha Touch Stores Sort tutorial

Now we need to include the Sencha Touch libraries in the index.html. My file looks like the screenshot below. Make sure that your index.html file is pointing to the directory where you placed your copies of the Sencha Touch libraries.

Tutorial: How to sort Sencha Touch Store

Defining a Sencha Touch Model

Next we need to create a Sencha Touch Model for the records that we will place in the Store. In the Model directory, create the Product.js file and type the following model definition:

Ext.define('App.model.Product', {
    extend: 'Ext.data.Model',
    config: {
        idProperty: 'productCode',
        fields: [
            { name: 'productCode', type: 'string' },
            { name: 'productName', type: 'string' },
            { name: 'productLine', type: 'string' }
        ]
    }
});

We will declare this model in the models config of the app in the app.js file:

Ext.application({
    name: 'App',
    models: ['Product'],
    launch: function () {

    }
});

Creating the Store

We will also create the Products.js file in the Store directory. This is the definition of the store:

Ext.define('App.store.Products', {
    extend: 'Ext.data.Store',
    config: {
        model: 'App.model.Product',
        remoteSort: false,
        sorters: [{
            property: 'productCode',
            direction: 'ASC'
        }],
        data: [
            { productCode: 'S10_1678', productName: '1969 Harley Davidson Ultimate Chopper', productLine: 'Motorcycles' },
            { productCode: 'S10_1949', productName: '1952 Alpine Renault 1300', productLine: 'Classic Cars' },
            { productCode: 'S10_2016', productName: '1996 Moto Guzzi 1100i', productLine: 'Motorcycles' },
            { productCode: 'S10_4698', productName: '2003 Harley-Davidson Eagle Drag Bike', productLine: 'Motorcycles' },
            { productCode: 'S12_1666', productName: '1958 Setra Bus', productLine: 'Trucks and Buses' },
            { productCode: 'S10_4757', productName: '1972 Alfa Romeo GTA', productLine: 'Classic Cars' },
            { productCode: 'S12_4473', productName: '1957 Chevy Pickup', productLine: 'Trucks and Buses' },
            { productCode: 'S18_1097', productName: '1940 Ford Pickup Truck', productLine: 'Trucks and Buses' }
        ]    }
});

Pay attention to the remoteSort config, which defines if the sort will be performed on the client or deferred to the server. This config’s value is false by default. We are setting it explicitly for demonstration purposes.

The sorters config is what we use to define the sorters of the store at definition time. This config takes an array of Sorter instances. The two most important configs of a Sorter object are “property” and “direction”. We use the “property” config to define the Model’s field that the data will be sorted on. The “direction” property defines the direction to sort by, ascending or descending. A third config, sorterFn, is very important as well. We will look at it in detail later in this tutorial.

Note also that we have harcoded a few records using the data config. In a real-life app the Store would most likely pull these data from the server.

Let’s make sure to declare the store in the stores config of the application in the app.js file:

Ext.application({
    name: 'App',
    models: ['Product'],
    stores: ['Products'],
    launch: function () {

    }
});

Defining a Handler for the Store’s Load Event

With the model and store in place, we can proceed to look at the different sort features of a Sencha Touch Store. In the app.js file, let’s first define a handler for the load event of the store. The handler will allow us to perform sorting operations once the store has been loaded.

Ext.application({
    name: 'App',
    models: ['Product'],
    stores: ['Products'], 
    launch: function () {

        // Use the getStore methodto get a reference to a store added via the stores config.
        var productsStore = Ext.getStore('Products');

        productsStore.on({
            load: this.onStoreLoad
        });
    },

    onStoreLoad: function (store, records) {

    }
});   

After reading this you might object that our store is already loaded with hardcoded data and it is not necessary to reload it. True, but I want you to get familiar with this approach because in most real-life apps you will not have hardcoded data in the stores.

Using a Sencha Touch Store’s Sorters Config

The first sorting feature of the Store Class that we will explore is the sorters config. Remember that we defined the below sorters config in the Products Store:

sorters: [{
    property: 'productCode',
    direction: 'ASC'
}]

Remember as well that the “property” config of a Sorter specifies the Model’s field that the data will be sorted on, and that the “direction” property defines the direction to sort by, ascending or descending.

Let’s simply render the records in the Store, which will allow us to confirm that they are sorted by product code ascending. In the onStoreLoad handler, add the following code:

onStoreLoad: function (store, records) {

    // Render records sorted by product code as defined in the sorters config of the store
    console.log("Records sorted by product code asc:");
    store.each(function (record) {
        console.log('- ' + record.get('productName'));
    });
}

If we run the app in Google Chrome and open the JavaScript Console, we should see the log generated by the code:

Sencha Touch sorters example

The Sort Method of a Sencha Touch Store

Next up in our demonstration is the sort method of the Store, which sorts the Store’s records by one or more properties. Let’s add this code to the onStoreLoad handler:

// You can use the sort method to sort the store
store.sort([
    {
        property:'productName',
        direction: 'DESC'
    }
]);

console.log("Records sorted by product name desc:");
store.each(function (record) {
    console.log('- ' + record.get('productName'));
});

We just sorted the records by product name descending. Refreshing the app in Google Chrome should produce a product names list similar to this:

Sencha Touch Store sorters example

We used one sort argument in this example, but the Store accepts multiple arguments. When we invoke the sort method, these arguments are converted to an array Sorter instances. The sorting of the records is delegated to internal Ext.util.Collection of the Store.

We can also pass a property name to the sort method:

store.sort("productName");

When invoked this way, the Store uses an internal ASC/DESC toggler. Therefore, we can toggle the product name sort by doing this:

store.sort("productName");
store.sort("productName");

Using the SetSorters Method of a Sencha Touch Store

We use the setSorters method to set the value of the Store’s sorters config. Let’s add the following code to the onStoreLoad handler so we can see the setSorters method in action:

// You can use the setSorters method to apply sorters to the store.
store.setSorters([
    {
        // Sort by first letter of last name, in descending order
        sorterFn: function (record1, record2) {
            var productLine1 = record1.get('productLine'),
                productLine2 = record2.get('productLine');

            return productLine1.localeCompare(productLine2);
        },
        direction: 'ASC'
    },
    {
        // Sort by first letter of last name, in descending order
        sorterFn: function (record1, record2) {
            var productName1 = record1.get('productName'),
                productName2 = record2.get('productName');

            return productName1.localeCompare(productName2);
        },
        direction: 'DESC'
    }
]);

console.log("Records sorted by product line asc, then by product name desc:");
store.each(function (record) {
    console.log('- ' + record.get('productName'));
});

The first interesting thing that we did when invoking setSorters is that we defined two sorters. This is perfectly possible, as you already know. In this case we are sorting by product line first, and then by product name.

Inside the sorters, we are using the sorterFn config instead of the property config. The sorterFn allows us to define a function that compares the records to be sorted and produces the sort that we desire. This function is passed two records. It should return -1, 0 or 1 depending on whether the first record should be sorted before, at the same level, or after the second record.

While our sorterFn functions are simply comparing product lines and product names, it should be apparent to you that the sorterFn allows us to perform more complex comparisons and hence more complex sorts.

One more check in the browser will show the results of invoking setSorters:

Sencha Touch Store setSorters example

Next Steps

The different sorting capabilities available in a Sencha Touch Store allow us to perform sort operations on one or multiple properties of the Store’s records. This tutorial focused on client-side sorting – a powerful feature in real-life apps.

A no less powerful feature is server-side sorting, which is also possible with Sencha Touch Stores and a bit of server-side coding. My next Sencha Touch Stores sort tutorial will show you how this is done.

Are You Getting Started with Mobile Web Apps?

If you are just getting started with mobile web development, MiamiCoder’s Sencha Touch and jQuery Mobile books will teach you, step by step, how to create Sencha Touch and jQuery Mobile applications. If you like to learn by doing, these books are ideal for you.

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
java ,mobile ,frameworks ,tips and tricks ,tools & methods ,sencha touch

Published at DZone with permission of Jorge Ramon, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}