又是项目需求。对带有复选框的GridPanel,需要有方法可以获得所有当前勾选行的某一列的数据之和。
Ext本身有一个GridSummary.js的扩展。不过我大概看了一下(没仔细研究),没针对checkBox勾选行的统计功能。因而对Ext.grid.GridPanel做了无情的扩展,代码如下:
Ext.grid.HsGridPanel = Ext.extend(Ext.grid.GridPanel,{
......
/**
* 返回已经勾选所有行指定列的值的sum
* @author weic
* @param sumColumnName 要累加的列
* @param fastCount [true/false,空]true是快速计算,牺牲一点小数的准确度,默认(不写这个属性的话)是false
* @param fixLength 限制返回值的小数位数
*/
getSelectionSum:function(sumColumnName, fastCount, fixLength){
function floatAdd(arg1,arg2){
var r1,r2,m;
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2))
return (arg1*m+arg2*m)/m
}
var selectedLines = this.getSelectionModel().getSelections();
if(selectedLines.length > 0){
var sum = 0;
if(fastCount == undefined || !fastCount){
for(var i=0; i<selectedLines.length; i++){
sum = floatAdd(sum,selectedLines[i].get(sumColumnName));
}
}
else if(fastCount){
for(var i=0; i<selectedLines.length; i++){
sum = sum + selectedLines[i].get(sumColumnName);
}
}
}
if(fixLength){
//alert("限制小数位" + fixLength);
var tempSum = sum;
try{ sum = sum.toFixed(fixLength) } catch(e){ sum = tempSum}
}
//alert(sum);
return sum;
}
......
}
使用的时候,GridPanel的实例如果是grid, 就调用 grid.getSelectionSum('列名');可以获得这个列的勾选值的总和。
当给了这个方法第2个参数的时候 grid.getSelectionSum('列名',true);就调用快速计算,在大数据量的时候速度比较高,但会损失高位小数的精度。设置为false就不会。
第3个参数(也可以不写),指定小数的保留位数。
截图如下:
1.快速计算------grid.getSelectionSum('price',true);
2. 精确计算------grid.getSelectionSum('price');
3. 保留一位小数------grid.getSelectionSum('price',true,1);