问题
I'm trying to enable the ability to right click on a data point on the chart. It seems to implement this feature two things need to happen:
Add a listener for the right click even "context menu" event. l looked at #1952 where they added a listener for the double click event. I'm assuming that you would do that same.
Once there is a hook for it, I can then get the x and y coordinate and overlay a custom dev menu.
Question:
- Is this the best approach for this or is there any easier way?
- Is there a way to extend c3 vs modifying the original code base. I took a look at https://github.com/c3js/c3/releases/tag/0.3.0 and it's not really clear what I would do.
Would i just do something like this:
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 () {}
);
}
;
I'm also doing this in typescript so i'm having issue with the first line since none of these are defined in the scope of my class and not sure how I would keep the underlying implementation but extend it.
const $$ = this, d3 = $$.d3, config = $$.config;
Thanks, Derek
回答1:
Rather than change the c3 code itself, it's probably better to listen to events on the .c3-event-rect class using the .onrendered hook:
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));
})
;
}
Add that to your chart configuration
http://jsfiddle.net/5x1nyqut/21/
Updated fiddle^^^, because latest version of c3 has a bug. This fiddle references a previous working version of c3 (0.4.22)
来源:https://stackoverflow.com/questions/49421072/how-to-add-update-c3-charts-to-listen-for-a-right-click-mouse-event