我正在尝试使用Slick Grid和DataView来计算列总数,如本例中的http://mleibman.github.io/SlickGrid/examples/example-grouping。但是,我不想对行进行分组,所以我尽量不向dataView.setGrouping(..)传递getter和formatter。方法,但在我的表中,它显示了文本为'undefined‘的分组行。它确实正确地计算了我的总数。如何删除不必要的分组行?
这就是我正在尝试的:
dataView.setGrouping({
aggregators: [
new Slick.Data.Aggregators.Sum('someField1'),
new Slick.Data.Aggregators.Sum('someField2')
]
});
发布于 2015-05-21 19:49:30
因此,对于“如何在没有分组的情况下计算总和”的问题,我知道这个问题很老了,但是由于我必须自己做,并且找不到任何有效的方法,我决定花一些时间来解决这个问题,现在我分享我的解决方案。SlickGrid的代码只会在分组后计算总和,我猜这就是聚合器的作用,但我深入研究了DataView代码,并提出了一个解决方案,它只有几行代码,但它工作得很好,并且使用了你已经知道的和已经定义的巧妙的聚合器。我从DataView获取了两个函数,其中一些是私有的,这就是为什么你需要在你的代码中重新复制它的原因。所以最后的代码是一个函数名CalculateTotalByAggregator()
,它将在内部调用另外两个函数。
注意:注意dataview.getItems()
,dataview
必须来自您的代码,并且可能拼写不同。
/** Calculate the total of an existing field from the datagrid
* @param object aggregator
* @return mixed total
*/
function CalculateTotalByAggregator(agg) {
var constructorName = agg.constructor.name; // get constructor name, ex.: SumAggregator
var type = constructorName.replace(/aggregator/gi, '').toLowerCase(); // remove the word Aggregator and make it lower case, ex.: SumAggregator -> sum
var totals = new Slick.GroupTotals();
var fn = compileAccumulatorLoop(agg);
fn.call(agg, dataview.getItems());
agg.storeResult(totals);
return totals[type][agg.field_];
}
/** This function comes from SlickGrid DataView but was slightly adapted for our usage */
function compileAccumulatorLoop(aggregator) {
aggregator.init();
var accumulatorInfo = getFunctionInfo(aggregator.accumulate);
var fn = new Function(
"_items",
" for (var " + accumulatorInfo.params[0] + ", _i=0, _il=_items.length; _i<_il; _i++) {" +
accumulatorInfo.params[0] + " = _items[_i]; " +
accumulatorInfo.body +
"}"
);
fn.displayName = "compiledAccumulatorLoop";
return fn;
}
/** This function comes from Slick DataView, but since it's a private function, you will need to copy it in your own code */
function getFunctionInfo(fn) {
var fnRegex = /^function[^(]*\(([^)]*)\)\s*{([\s\S]*)}$/;
var matches = fn.toString().match(fnRegex);
return {
params: matches[1].split(","),
body: matches[2]
};
}
然后在客户端,您只需要调用CalculateTotalByAggregator(agg)
函数和一个有效的Slick.Aggregators
对象,例如:
// use any valid Slick Aggregator object and pass it to the function
var agg = new Slick.Data.Aggregators.Sum("Hours");
var totalHours = gridObject.CalculateTotalByAggregator(agg);
// or on a 1 liner
var totalHours = gridObject.CalculateTotalByAggregator(new Slick.Data.Aggregators.Sum("Hours"));
这只是几行代码,但在这种方式下,不需要重写一个函数来做求和,另一个函数做平均,等等。您只需使用您已经在使用的灵活的聚合器,就可以了。简单:)
https://stackoverflow.com/questions/20753455
复制相似问题