YUI recommends YUI3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

This documentation is no longer maintained.

YUI Library Examples: DataTable Control: Client-side Sorting

DataTable Control: Client-side Sorting

A custom sort handler has been defined in this example to enable custom nested sorting, such that clicking on the "States" Column will sort by states, and then by area code.

Sample Code for this Example

Data:

1YAHOO.example.Data = { 
2    areacodes: [ 
3        {areacode: "201", state: "New Jersey"}, 
4        {areacode: "202", state: "Washington, DC"}, 
5        {areacode: "203", state: "Connecticut"}, 
6        ... 
7    ] 
8
view plain | print | ?

CSS:

1/* No custom CSS. */ 
view plain | print | ?

Markup:

1<div id="sort"></div> 
view plain | print | ?

JavaScript:

1YAHOO.util.Event.addListener(window, "load"function() { 
2    YAHOO.example.CustomSort = function() { 
3        // Custom sort handler to sort by state and then by areacode 
4        // where a and b are Record instances to compare 
5        var sortStates = function(a, b, desc) { 
6            // Deal with empty values 
7            if(!YAHOO.lang.isValue(a)) { 
8                return (!YAHOO.lang.isValue(b)) ? 0 : 1; 
9            } 
10            else if(!YAHOO.lang.isValue(b)) { 
11                return -1; 
12            } 
13 
14            // First compare by state 
15            var comp = YAHOO.util.Sort.compare; 
16            var compState = comp(a.getData("state"), b.getData("state"), desc); 
17 
18            // If states are equal, then compare by areacode 
19            return (compState !== 0) ? compState : comp(a.getData("areacode"), b.getData("areacode"), desc); 
20        }; 
21 
22        var myColumnDefs = [ 
23            {key:"areacode",label:"Area Codes",sortable:true}, 
24            {key:"state",label:"States",sortable:true,sortOptions:{sortFunction:sortStates}} 
25        ]; 
26 
27        var myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.areacodes.slice(0,25)); 
28        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
29        myDataSource.responseSchema = { 
30            fields: ["areacode","state"
31        }; 
32 
33        var myDataTable = new YAHOO.widget.DataTable("sort", myColumnDefs, 
34                myDataSource, {sortedBy:{key:"areacode", dir:"asc"}}); 
35                 
36        return { 
37            oDS: myDataSource, 
38            oDT: myDataTable 
39        }; 
40    }(); 
41}); 
view plain | print | ?

Copyright © 2013 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings