如何添加更新 c3 图表以监听右键单击鼠标事件?

How to add update c3 charts to listen for a right click mouse event?

我正在尝试启用右键单击图表上数据点的功能。似乎要实现此功能需要做两件事:

为右键单击甚至 "context menu" 事件添加侦听器。我查看了#1952,他们在其中为双击事件添加了一个侦听器。我假设你也会这样做。

一旦有了它的钩子,我就可以获取 x 和 y 坐标并覆盖自定义开发菜单。

问题:

  1. 这是最好的方法还是有更简单的方法?
  2. 有没有办法扩展 c3 与修改原始代码库。我看了一下 https://github.com/c3js/c3/releases/tag/0.3.0 并不太清楚我会做什么。

我会做这样的事情吗:

c3.chart.internal.generateEventRectsForSingleX = (eventRectEnter) => {
               const $$ = this, d3 = $$.d3, config = $$.config;
               eventRectEnter.append("rect")
                   .attr("class", $$.classEvent.bind($$))
                   .style("cursor", config.data_selection_enabled && config.data_selection_grouped ? "pointer" : null)
                   .on('mouseover', function (d) {
                       ....
                   })
                   .on('mouseout', function (d) {
                      ....
                   })
                   .on('mousemove', function (d) {
                     ...
                   })
                   .on('click', function (d) {
                     ...
                   })
                   .on('contextmenu', function (d) {
                      < Add Logic for call back to render the menu >
                   })
                   .call(
                       config.data_selection_draggable && $$.drag ? (
                           d3.behavior.drag().origin(Object)
                               .on('drag', function () { $$.drag(d3.mouse(this)); })
                               .on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
                               .on('dragend', function () { $$.dragend(); })
                       ) : function () {}
                   );
}

;

我也在打字稿中这样做,所以我对第一行有疑问,因为其中 none 是在我的 class 范围内定义的,我不确定我将如何保留底层实现,但对其进行扩展。

const $$ = this, d3 = $$.d3, config = $$.config;

谢谢, 德里克

与其更改 c3 代码本身,不如使用 .onrendered 挂钩在 .c3-event-rect class 上监听事件:

onrendered: function () {
    d3.select("#chart").selectAll(".c3-event-rect")
    .on("contextmenu", function (d,i) {
        d3.event.preventDefault(); // prevent default menu
        var vals = chart.data().map (function (series) {
            var name = series.id;
                return {
                name: name, 
                value: chart.data.values(name)[d.x]}; // d.x is the index
            }
        );
        alert ("data: "+JSON.stringify(vals));
    })
  ;
}

将其添加到您的图表配置中

http://jsfiddle.net/5x1nyqut/21/

已更新fiddle^^^,因为最新版本的c3有bug。此 fiddle 引用了 c3 (0.4.22) 的先前工作版本