Created
April 18, 2012 23:35
-
-
Save minhnc/2417385 to your computer and use it in GitHub Desktop.
Flexible Object Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var win = Ti.UI.createWindow(); | |
var data = []; | |
for(var i = 0; i < 5; i++) { | |
data.push({title : 'Title ' + i, id : i.toString(), addr : 'Addr ' + i}); | |
} | |
var table = Ti.UI.createTableView({ | |
data : data, | |
_data : data | |
}) | |
win.add(table); | |
win.open(); | |
/** | |
* Can sort by any field, ASC or DESC, and can apply custom function by primer | |
*/ | |
var sort_by = function(field, reverse, primer) { | |
var key = function(x) { | |
return primer ? primer(x[field]) : x[field] | |
}; | |
return function(a, b) { | |
var A = key(a), B = key(b); | |
return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1,1][+!!reverse]; | |
} | |
} | |
setTimeout(function(){ | |
var newData = table._data; | |
newData = newData.sort( sort_by('id', false, parseInt) );// Sort DESC | |
table.setData([]); | |
table.setData(newData); | |
table._data = newData; | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment