DC.JS点击选择栏

DC.JS Selecting a Bar on Click

本文关键字:选择 JS DC      更新时间:2023-09-26

当用户单击特定条形图时,我正试图调用条形图上的函数。我意识到我需要使用renderlet向render函数添加一个监听器,然后从那里创建一个每个栏的分组,其中将添加一个点击事件。

假设使用任何通用条形图,我称之为:

barChart.on('renderlet', function(chart, filter)
{
    // TODO Select the bars here and add an on click function
});

唯一的问题是,我无法找到如何使用该图表对象在条形图上执行d3.select调用。当我把它倒出来的时候,我看不到物体里有任何像酒吧的东西。

对于这种事情,最简单的方法就是找到源代码。在这种情况下,

    var enter = bars.enter()
        .append('rect')
        .attr('class', 'bar')

https://github.com/dc-js/dc.js/blob/develop/src/bar-chart.js#L90-L92

所以选择器是rect.bar。此外,方便的方法chart.selectAll()比直接使用d3要好,因为它只会在当前图表中进行选择。

最后,为了避免践踏dc.js内部使用的事件,您可能需要为事件处理程序命名名称空间。

加起来,

barChart.on('renderlet.barclicker', function(chart, filter)
{
    chart.selectAll('rect.bar').on('click.custom', function(d) {
        // use the data in d to take the right action
    });
});