【问题标题】:How to use ChartJS object in a click event handler?如何在单击事件处理程序中使用 ChartJS 对象?
【发布时间】:2018-03-01 03:53:10
【问题描述】:

我在仪表板页面上绘制了 3 个 ChartJS 对象。我还在同一页面中使用 echarts.js 来绘制饼图。我在饼图上有一个点击事件,其中在 ChartJS 图表上为每个饼图的点击事件绘制了不同的数据。所以我在饼图的点击事件中使用 ChartJS 对象。但是,即使我在全局范围内定义了 ChartJS 对象,它在处理程序中也变得未定义。 我得到了 destroy() 的错误为“Uncaught TypeError: Cannot read property 'destroy' of undefined”。

我的问题是如何在 echarts 点击事件处理程序中访问 ChartJS 对象?

请参考我下面的代码示例:

pie.on('click', function (params) { //pie is the object of echart 
  console.log(myChart);//printing myChart results "undefined" in console
  var thatState = params.name;
  myChart.destroy();
  waitChart.destroy();
  myBarChart.destroy();
  console.log("destroyed!");

  //myChart,waitChart,myBarChart are the objects of 
  // chartJS. I'm destroying those to redraw the charts with new data on 
  // click event of pies.
..............
........
});

【问题讨论】:

    标签: javascript jquery chart.js echarts


    【解决方案1】:

    首先,确保它是真正全局的:

    console.log(window.myChart);
    

    1:尝试以某种方式将其作为参数传递(如果可能):

    pie.on('click', function(params, myChart) {
        console.log(myChart);
    });
    

    2:尝试 ES6 箭头符号,以便能够访问功能块之外的范围:

    pie.on('click', (params) => {
        console.log(window.myChart);
    });
    

    3:映射到this,在功能块中访问:

    this.myChart = myChart || window.myChart;
    pie.on('click', (params) => {
        console.log(this.myChart);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 2015-12-22
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多