Items are, in general, returned in an indeterminate order. This isn't always what you want to happen; there are definite cases where sorting items based on specific attributes is important. Fortunately, you do not have to do the sorting yourself because dojo.data provides a mechanism to do it for you. The mechanism is just another option passed to fetch, the sort array.
The sort array will look something like the following example:
var sortKeys = [{attribute: "aisle", descending: true}];
Each sort key has an attribute, which should be an attribute in the data store item, and a descending boolean flag. If an attribute passed isn't an actual attribute of the item, it will generally be ignored by the sorting; it is treated as an undefined comparison.
For compound sorts, you can define as many sort keys as you want. The order in the array defines which keys take priority over other keys when sorting. The following example shows this:
var sortKeys = [
{attribute: "aisle", descending: true},
{attribute: "name", descending: false}
];
For this example, we'll use the ItemFileReadStore data source:
{ identifier: 'name',
items: [
{ name: 'Adobo', aisle: 'Mexican' },
{ name: 'Balsamic vinegar', aisle: 'Condiments' },
{ name: 'Basil', aisle: 'Spices' },
{ name: 'Bay leaf', aisle: 'Spices' },
{ name: 'Beef Bouillon Granules', aisle: 'Soup' },
...
{ name: 'Vinegar', aisle: 'Condiments' },
{ name: 'White cooking wine', aisle: 'Condiments' },
{ name: 'Worcestershire Sauce', aisle: 'Condiments' }
{ name: 'pepper', aisle: 'Spices' }
]
}
Now, assume you want to sort the items in the store by aisle first, then by name. The following code snippet would do this:
var store = new dojo.data.ItemFileReadStore({url: "pantryStore.json"});
var sortKeys = [
{attribute: "aisle", descending: true},
{attribute: "name", descending: false}
];
store.fetch({
sort: sortKeys;
onComplete:
...
});
//When onComplete is called, the array of items passed into it
//should be sorted according to the denoted sort array.