因此,对于“如何在不分组的情况下计算总数”这个问题,我知道这个问题已经过时了,但是由于我必须自己做,找不到任何可行的方法,所以我决定花一些时间来解决这个问题,现在我正在分享我的解决方案。 SlickGrid 的代码只会在分组后计算总数,我猜这就是聚合器的用途,但我挖掘了 DataView 代码并提出了一个解决方案,它是几行代码,但它工作得很好,并且使用了你的 Slick 聚合器已经知道并且已经定义了。我从 DataView 中获取了 2 个函数,其中一些是私有的,因此您也需要在代码中重新复制它。所以最终代码是 1 个函数名称 CalculateTotalByAggregator(),它将在内部调用 2 个其他函数。
注意:注意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"));
这是几行代码,但这样就不需要重写一个函数来求和,另一个函数来做平均等等......您只需使用您已经使用的 Slick Aggregators 就可以了..简单:)