how can I condense this?
I have multiple datagrids with about 10-15 columns total. I have a numeric sortCompareFunction for each column. At the moment, I have a separate function for each sort compare I do....each does the sorting numerically. I'm guessing I could condense functions sort1, sort2, sort3, etc into 1 function but I can't figure out how:
private function sort1(obj1:Object, obj2:Object):int{
var value1:Number=(obj1.zip==''||obj1.zip==null)?null:new Number(obj1.zip);
var value2:Number=(obj2.zip==''||obj2.zip==null)?null:new Number(obj2.zip);
r开发者_JS百科eturn ObjectUtil.numericCompare(value1, value2);
}
private function sort2(obj1:Object, obj2:Object):int{
var value1:Number=(obj1.somenumbers==''||obj1.somenumbers==null)?null:new Number(obj1.somenumbers);
var value2:Number=(obj2.somenumbers==''||obj2.somenumbers==null)?null:new Number(obj2.somenumbers);
return ObjectUtil.numericCompare(value1, value2);
}
private function sort3(obj1:Object, obj2:Object):int{
var value1:Number=(obj1.morenumbers==''||obj1.morenumbers==null)?null:new Number(obj1.morenumbers);
var value2:Number=(obj2.morenumbers==''||obj2.morenumbers==null)?null:new Number(obj2.morenumbers);
return ObjectUtil.numericCompare(value1, value2);
}
...and on and on
One way would be to create a function to create compare functions:
private function createCompareFunc(propertyName:String):Function {
return function(obj1:Object, obj2:Object):int {
return ObjectUtil.numericCompare(Number(obj1[propertyName]),
Number(obj2[propertyName]));
}
}
Then set your compare function like this for each column:
dataGridColumn1.sortCompareFunction = createCompareFunc("property1");
The null and empty checks are unnecessary since Number()
automatically converts those to 0.
This will help simplify your code a bit:
private function genericSort(obj1:Object, obj2:Object,column:String):int{
var value1:Number=(obj1[column]==''||obj1[column]==null)?null:new Number(obj1[column]);
var value2:Number=(obj2[column]==''||obj2[column]==null)?null:new Number(obj2[column]);
return ObjectUtil.numericCompare(value1, value2);
}
private function sort1(obj1:Object, obj2:Object):int{
return genericSort(obj1, obj2, 'zip');
}
private function sort2(obj1:Object, obj2:Object):int{
return genericSort(obj1, obj2, 'someNumbers');
}
private function sort3(obj1:Object, obj2:Object):int{
return genericSort(obj1, obj2, 'moreNumbers');
}
And it is the approach I've used in the past. Unfortunately, in the sortCompareFunction there is no way to access the column being clicked to get the dataField property.
精彩评论