异步加载Chart.js工具提示信息

时间:2019-12-12 20:42:09

标签: javascript chart.js bar-chart

我知道我们可以使用以下代码加载图表工具提示的信息:

window.myLine = new Chart(chart, {
  type: 'line',
  data: lineChartData,
  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: function(tooltipItems, data) {
          return tooltipItems.yLabel + ' €';
        }
      }
    },
  }
});

问题是,就我而言,我需要调用一个函数并异步返回值;可能会显示一个微调框,直到答案准备好为止。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以改为异步调用chart.js update()方法。如果标签应取决于用户将哪个数据点悬停,则可能还需要使用递归。

window.myLine = new Chart(chart, {
  type: 'line',
  data: lineChartData,
  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: asyncTooltipLabel
      }
    },
  }
});

function asyncTooltipLabel(tooltipItems, data) {
  // some asynchronous function call
  setTimeout(function() {
    // when asyncronous result comes
    const result = (tooltipItems[0].index * 2) + ' €';

    const newTooltipConfig = {
       enabled: true,
       mode: 'single',
       callbacks: {
           label: function(newTooltipItems, newData) {
              if (newTooltipItems[0].index === tooltipItems[0].index && newTooltipItems[0].datasetIndex === tooltipItems[0].datasetIndex) return result;
              else asyncTooltipLabel(newTooltipItems, newData);
           }
       }
    }

    // apply new tooltip config
    window.myLine.options.tooltips = newTooltipConfig;
    window.myLine.update();
  }, 2000);
}
相关问题