2 * @class Ext.util.Sorter
4 * Represents a single sorter that can be applied to a Store
6 Ext.define('Ext.util.Sorter', {
9 * @cfg {String} property The property to sort by. Required unless {@link #sorter} is provided
13 * @cfg {Function} sorterFn A specific sorter function to execute. Can be passed instead of {@link #property}
17 * @cfg {String} root Optional root property. This is mostly useful when sorting a Store, in which case we set the
18 * root to 'data' to make the filter pull the {@link #property} out of the data object of each item
22 * @cfg {Function} transform A function that will be run on each value before
23 * it is compared in the sorter. The function will receive a single argument,
28 * @cfg {String} direction The direction to sort by. Defaults to ASC
32 constructor: function(config) {
35 Ext.apply(me, config);
38 if (me.property == undefined && me.sorterFn == undefined) {
39 Ext.Error.raise("A Sorter requires either a property or a sorter function");
43 me.updateSortFunction();
48 * Creates and returns a function which sorts an array by the given property and direction
49 * @return {Function} A function which sorts by the property/direction combination provided
51 createSortFunction: function(sorterFn) {
53 property = me.property,
54 direction = me.direction || "ASC",
55 modifier = direction.toUpperCase() == "DESC" ? -1 : 1;
57 //create a comparison function. Takes 2 objects, returns 1 if object 1 is greater,
58 //-1 if object 2 is greater or 0 if they are equal
59 return function(o1, o2) {
60 return modifier * sorterFn.call(me, o1, o2);
66 * Basic default sorter function that just compares the defined property of each object
68 defaultSorterFn: function(o1, o2) {
70 transform = me.transform,
71 v1 = me.getRoot(o1)[me.property],
72 v2 = me.getRoot(o2)[me.property];
79 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
84 * Returns the root property of the given item, based on the configured {@link #root} property
85 * @param {Object} item The item
86 * @return {Object} The root property of the object
88 getRoot: function(item) {
89 return this.root == undefined ? item : item[this.root];
92 // @TODO: Add docs for these three methods
93 setDirection: function(direction) {
95 me.direction = direction;
96 me.updateSortFunction();
101 me.direction = Ext.String.toggle(me.direction, "ASC", "DESC");
102 me.updateSortFunction();
105 updateSortFunction: function() {
107 me.sort = me.createSortFunction(me.sorterFn || me.defaultSorterFn);