我有多个数据网格,总共约10-15列。我为每列都有一个数字sortCompareFunction。目前,我对每种排序都有一个单独的功能比较....每个都按数字排序。我猜我可以将函数sort1,sort2,sort3等压缩为1函数,但我无法弄清楚如何:
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);
return 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
答案 0 :(得分:4)
一种方法是创建一个函数来创建比较函数:
private function createCompareFunc(propertyName:String):Function {
return function(obj1:Object, obj2:Object):int {
return ObjectUtil.numericCompare(Number(obj1[propertyName]),
Number(obj2[propertyName]));
}
}
然后为每列设置这样的比较函数:
dataGridColumn1.sortCompareFunction = createCompareFunc("property1");
由于Number()
会自动将这些检查转换为0,因此无需进行空检查和空检查。
答案 1 :(得分:1)
这将有助于简化您的代码:
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');
}
这是我过去使用过的方法。不幸的是,在sortCompareFunction中,无法访问被单击的列以获取dataField属性。