Yahoo! Developer Network Home - Help

YUI Library Examples: DataTable Control (beta): Client-side Sorting

DataTable Control (beta): 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.

Area Codes
States
201
New Jersey
202
Washington, DC
203
Connecticut
204
Manitoba, Canada
205
Alabama
206
Washington
207
Maine
208
Idaho
209
California
210
Texas
212
New York
213
California
214
Texas
215
Pennsylvania
216
Ohio
217
Illinois
218
Minnesota
219
Indiana
224
Illinois
225
Louisiana
227
Maryland
228
Mississippi
229
Georgia
231
Michigan
234
Ohio

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 = new function() { 
3        // Custom sort handler to sort by state and then by areacode 
4        // where a and b are Record instances to compare 
5        this.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:this.sortStates}} 
25        ]; 
26 
27        this.myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.areacodes.slice(0,25)); 
28        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
29        this.myDataSource.responseSchema = { 
30            fields: ["areacode","state"
31        }; 
32 
33        this.myDataTable = new YAHOO.widget.DataTable("sort", myColumnDefs, 
34                this.myDataSource, {sortedBy:{key:"areacode", dir:"asc"}}); 
35    }; 
36}); 
view plain | print | ?

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings