在闪亮的应用程序中单击nvd3图表的事件(作为自定义输出绑定)

click event for nvd3 chart (as a custom output binding) in a shiny application

本文关键字:自定义 输出 绑定 事件 应用程序 单击 nvd3      更新时间:2023-09-26

编辑:

解决问题:.useInteractiveGuideline(true)改为.useInteractiveGuideline(false)

原件:

我试图使用NVD3折线图修改自定义输出绑定示例,并在NVD3图表上附加一个点击事件侦听器。我修改了linechart-bindings.js文件,如下所示。唯一的修改是这部分代码(整个文件也被复制到下面,所以你可以看到我在那里添加了代码片段(:

    chart.lines.dispatch.on("elementClick", function( e ) {
        console.log(e);
    });

该应用程序启动时没有问题,但当我单击图表时,没有控制台日志打印输出。可能我的方法过于简单化了,缺少了一些明显的部分。知道怎么解决这个问题吗?

完整的linechar-bindings.js文件:

// Put code in an Immediately Invoked Function Expression (IIFE).
// This isn't strictly necessary, but it's good JavaScript hygiene.
(function() {
// See http://rstudio.github.io/shiny/tutorial/#building-outputs for
// more information on creating output bindings.
// First create a generic output binding instance, then overwrite
// specific methods whose behavior we want to change.
var binding = new Shiny.OutputBinding();
binding.find = function(scope) {
  // For the given scope, return the set of elements that belong to
  // this binding.
  return $(scope).find(".nvd3-linechart");
};
binding.renderValue = function(el, data) {
  // This function will be called every time we receive new output
  // values for a line chart from Shiny. The "el" argument is the
  // div for this particular chart.
  var $el = $(el);
  // The first time we render a value for a particular element, we
  // need to initialize the nvd3 line chart and d3 selection. We'll
  // store these on $el as a data value called "state".
  if (!$el.data("state")) {
    var chart = nv.models.lineChart()
      .margin({left: 100})
      .useInteractiveGuideline(true)
      .transitionDuration(350)
      .showLegend(true)
      .showYAxis(true)
      .showXAxis(true);
    chart.xAxis     //Chart x-axis settings
      .axisLabel('Time (ms)')
      .tickFormat(d3.format(',r'));
    chart.yAxis     //Chart y-axis settings
      .axisLabel('Voltage (v)')
      .tickFormat(d3.format('.02f'));
    chart.lines.dispatch.on("elementClick", function( e ) {
        console.log(e);
    });
    nv.utils.windowResize(chart.update);
    var selection = d3.select(el).select("svg");
    // Store the chart object on el so we can get it next time
    $el.data("state", {
      chart: chart,
      selection: selection
    });
  }
  // Now, the code that'll run every time a value is rendered...
  // Retrieve the chart and selection we created earlier
  var state = $el.data("state");
  // Schedule some work with nvd3
  nv.addGraph(function() {
    // Update the chart
    state.selection
      .datum(data)
      .transition(500)
      .call(state.chart);
    return state.chart;
  });
};
// Tell Shiny about our new output binding
Shiny.outputBindings.register(binding, "shinyjsexamples.nvd3-linechart");
})();

不是解决方案,而是解决方法:.useInteractiveGuideline(true)更改为.useInteractiveGuideline(false)