我正在构建一个仪表板来显示一些数据。我有几个图表和一个列出所有数据的表格。我正在尝试添加搜索功能来过滤图表。我有很多公司和每个公司的一些数据。因此,如果我搜索“Appl”,只有以“Appl”开头的公司会列在数据表中,图表也会反射(reflect)这一点。
我在当前实现中遇到的唯一问题是当我更改或清除此过滤器时。数据看起来不错,但图表呈现不正确。清除后它们不会返回到原来的位置,或者它们会以某种方式添加额外的数据。任何提示将不胜感激。
$("#table-search").on('input',function(){
text_filter(companyDimension,this.value);//companyDimension is the dimension for the data table
function text_filter(dim,q){
dashTable.filterAll();
var re = new RegExp(q,"i")
if (q!='')
{
dim.filter(function(d){
if (d.search(re)==0)
return d;
});
}
dc.redrawAll();
graphCustomizations(); }});
dc.js代码
var ndx = crossfilter(resource_data);
//Dimensions
companyDimension = ndx.dimension(function(d){
return d["Company Name"]
});
dashTable.width(800).height(800)
.dimension(companyDimension)
.group(function(d){
return "List of all Selected Companies";
})
.size(1774)
.columns([
function(d){return d["Company Name"]; },
function(d){return d["Revenue Source"];},
function(d){return d["Commodity"];},
function(d){return "$"+parseFloat(d["Revenue"]).formatMoney(0,'.',',');}
])
.sortBy(function(d){return d["Company Name"]})
.order(d3.ascending);
就是这样,图表只是在同一个交叉过滤器对象上使用不同的维度进行过滤。
我已经尝试对 text_filter 函数做几件事,例如 dim.filterAll()
、dim.filter(null)
、dc.renderAll ()
。当我检查维度中的数据时,每个过滤器前后都是正确的,其他图表似乎没有正确处理它。
我试过直接向 dc dataTable 添加一个基本过滤器,但我无法让它与自定义过滤器功能一起使用。所以我可以做一些像 dashTable.filter(q)
这样的事情,它会工作,但我必须给它完整的公司名称才能显示任何东西,但是当我应用它时图表会正确呈现并且去掉它。我试过使用 dashTable.filterHandler()
但它总是返回一个错误,但如果你知道如何让它工作,我会很好奇,因为我什至无法让它运行使用 dc.js 文档中的示例。
如有任何帮助,我们将不胜感激。
编辑:
这是大部分完整代码的 fiddle ,我将一些代码混在一起以使其正常工作。 http://jsfiddle.net/rbristow/HW52d/1/
要重现该错误,请在搜索框中输入一个字母然后将其清除并输入另一个字母,您可以看到总计未正确重置。
最佳答案
在这个 block 中:
if (q != '') {
dim.filter(function(d) {
if (d.search(re) == 0)
return d;
});
}
您的过滤器需要:
dim.filter(function(d) { return 0 == d.search(re); });
但是,如果 q == ''
,您没有对 dim
应用任何过滤器,所以它应该是
if (q != '') {
dim.filter(function(d) {
return 0 == d.search(re);
});
} else {
dim.filterAll();
}
解释:
在 crossfilter.js
中,过滤器回调的返回值是这样测试的:
if (!(filters[k = index[i]] & one) ^ (x = f(values[i], i))) {
if (x) filters[k] &= zero, added.push(k);
else filters[k] |= one, removed.push(k);
}
如果过滤器返回 true
并且项目已经在当前 View 中,则它不应该做任何事情。 真 ^ 真 -> 假
。
但在您的情况下,true
正在与字符串进行异或运算——请注意,这是按位异或,而不是逻辑异或,因为 Javascript 缺少逻辑异或——它将始终计算为true
值。因此,您希望过滤集中的值被放入 added
中,而这些值本应单独放置。
按位异或的使用很奇怪。我在 SO 上查看了这个和 Why is there no logical xor in JavaScript? 的最高投票答案包含“按位异或非常有用,但在我多年的编程生涯中,我从来不需要逻辑异或。”鉴于 crossfilter.js
强调性能,他们可能会放弃一些错误检查并希望使用快速的“数学”运算。
关于javascript - DC.js 数据表的自定义文本过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25083383/