イベントとアクション

ユーザーは操作によって対応するイベントをトリガーできます。開発者は、これらのイベントをリッスンすることでコールバック関数を処理できます。たとえば、新しいWebサイトへのジャンプ、ダイアログボックスのポップアップ、データのドリルダウンなどです。

イベント名とDOMイベントはどちらも小文字の文字列です。click イベントのリッスンバインディングの例を次に示します。

myChart.on('click', function(params) {
  // Print name in console
  console.log(params.name);
});

EChartsには2種類のイベントがあります。1つはユーザーがチャート内の要素をクリックまたはホバーしたときに発生するイベント、もう1つはユーザーがインタラクティブなアクションをトリガーしたときに発生するイベントです。たとえば、凡例選択の変更中にトリガーされる 'legendselectchanged' (この状況ではlegendselectedはトリガーされないことに注意してください)、データ領域のズーム中にトリガーされる 'datazoom' などです。

マウスイベントの処理

EChartsは一般的なマウスイベントをサポートしています:'click''dblclick''mousedown''mousemove''mouseup''mouseover''mouseout''globalout''contextmenu'。棒グラフをクリックした後に検索結果ページを開く例を次に示します。

// Init the ECharts base on DOM
var myChart = echarts.init(document.getElementById('main'));

// Config
var option = {
  xAxis: {
    data: [
      'Shirt',
      'Wool sweater',
      'Chiffon shirt',
      'Pants',
      'High-heeled shoes',
      'socks'
    ]
  },
  yAxis: {},
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }
  ]
};
// Use the option and data to display the chart
myChart.setOption(option);
// Click and jump to Baidu search website
myChart.on('click', function(params) {
  window.open(
    'https://www.google.com/search?q=' + encodeURIComponent(params.name)
  );
});

すべてのマウスイベントには、オブジェクトのデータを含むparamsが含まれています。

フォーマット

type EventParams = {
  // The component name clicked,
  // component type, could be 'series'、'markLine'、'markPoint'、'timeLine', etc..
  componentType: string,
  // series type, could be 'line'、'bar'、'pie', etc.. Works when componentType is 'series'.
  seriesType: string,
  // the index in option.series. Works when componentType is 'series'.
  seriesIndex: number,
  // series name, works when componentType is 'series'.
  seriesName: string,
  // name of data (categories).
  name: string,
  // the index in 'data' array.
  dataIndex: number,
  // incoming raw data item
  data: Object,
  // charts like 'sankey' and 'graph' included nodeData and edgeData as the same time.
  // dataType can be 'node' or 'edge', indicates whether the current click is on node or edge.
  // most of charts have one kind of data, the dataType is meaningless
  dataType: string,
  // incoming data value
  value: number | Array,
  // color of the shape, works when componentType is 'series'.
  color: string
};

マウスクリックされた場所を特定します。

myChart.on('click', function(params) {
  if (params.componentType === 'markPoint') {
    // Clicked on the markPoint
    if (params.seriesIndex === 5) {
      // clicked on the markPoint of the series with index = 5
    }
  } else if (params.componentType === 'series') {
    if (params.seriesType === 'graph') {
      if (params.dataType === 'edge') {
        // clicked at the edge of graph.
      } else {
        // clicked at the node of graph.
      }
    }
  }
});

queryを使用して、指定されたコンポーネントのコールバックをトリガーします

chart.on(eventName, query, handler);

querystringまたはObjectです。

stringの場合、フォーマットはmainTypeまたはmainType.subTypeです。例:

chart.on('click', 'series', function () {...});
chart.on('click', 'series.line', function () {...});
chart.on('click', 'dataZoom', function () {...});
chart.on('click', 'xAxis.category', function () {...});

Objectの場合、queryには複数の属性を含めることができます

{
  ${mainType}Index: number // component index
  ${mainType}Name: string // component name
  ${mainType}Id: string // component id
  dataIndex: number // data item index
  name: string // data item name
  dataType: string // date item type, such as 'node', 'edge'
  element: string // name of element in custom series.
}

例:

chart.setOption({
  // ...
  series: [
    {
      name: 'uuu'
      // ...
    }
  ]
});
chart.on('mouseover', { seriesName: 'uuu' }, function() {
  // when elements in series named 'uuu' triggered 'mouseover'
});

例えば

chart.setOption({
  // ...
  series: [
    {
      // ...
    },
    {
      // ...
      data: [
        { name: 'xx', value: 121 },
        { name: 'yy', value: 33 }
      ]
    }
  ]
});
chart.on('mouseover', { seriesIndex: 1, name: 'xx' }, function() {
  // when data named 'xx' in series index 1 triggered 'mouseover'.
});

例えば

chart.setOption({
  // ...
  series: [
    {
      type: 'graph',
      nodes: [
        { name: 'a', value: 10 },
        { name: 'b', value: 20 }
      ],
      edges: [{ source: 0, target: 1 }]
    }
  ]
});
chart.on('click', { dataType: 'node' }, function() {
  // call this method while the node of graph was clicked.
});
chart.on('click', { dataType: 'edge' }, function() {
  // call this method while the edge of graph was clicked.
});

例えば

chart.setOption({
  // ...
  series: {
    // ...
    type: 'custom',
    renderItem: function(params, api) {
      return {
        type: 'group',
        children: [
          {
            type: 'circle',
            name: 'my_el'
            // ...
          },
          {
            // ...
          }
        ]
      };
    },
    data: [[12, 33]]
  }
});
chart.on('mouseup', { element: 'my_el' }, function() {
  // when data named 'my_el' triggered 'mouseup'.
});

コールバック関数でデータベースからデータ名または系列名でクエリ結果を使用して、ポップアップを表示したり、チャートを更新したりできます。例を次に示します

myChart.on('click', function(parmas) {
  $.get('detail?q=' + params.name, function(detail) {
    myChart.setOption({
      series: [
        {
          name: 'pie',
          // using pie chart to show the data distribution in one column.
          data: [detail.data]
        }
      ]
    });
  });
});

コンポーネントインタラクションのイベント

EChartsのすべてのコンポーネントインタラクションは、対応するイベントをトリガーします。通常のイベントとパラメータは、イベントドキュメントに記載されています。

凡例イベントをリッスンする例を次に示します

// Show/hide the legend only trigger legendselectchanged event
myChart.on('legendselectchanged', function(params) {
  // State if legend is selected.
  var isSelected = params.selected[params.name];
  // print in the console.
  console.log(
    (isSelected ? 'Selected' : 'Not Selected') + 'legend' + params.name
  );
  // print for all legends.
  console.log(params.selected);
});

コードを書いてコンポーネントアクションを手動でトリガーする

ユーザーだけでなく、コードで手動で'legendselectchanged'などのイベントをトリガーできます。ツールチップの表示、凡例の選択に使用できます。

EChartsでは、myChart.dispatchAction({ type: '' })を使用して動作をトリガーします。これはすべてのアクションを管理し、動作を便利に記録できます。

一般的に使用される動作と対応するパラメータは、アクションに記載されています。

次の例は、dispatchActionを使用して円グラフの各セクターを1つずつ強調表示する方法を示しています。

option = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: [
      'Direct Access',
      'Email Marketing',
      'Affiliate Ads',
      'Video Ads',
      'Search Engines'
    ]
  },
  series: [
    {
      name: 'Access Source',
      type: 'pie',
      radius: '55%',
      center: ['50%', '60%'],
      data: [
        { value: 335, name: 'Direct Access' },
        { value: 310, name: 'Email Marketing' },
        { value: 234, name: 'Affiliate Ads' },
        { value: 135, name: 'Video Ads' },
        { value: 1548, name: 'Search Engines' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

let currentIndex = -1;

setInterval(function() {
  var dataLen = option.series[0].data.length;
  myChart.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: currentIndex
  });
  currentIndex = (currentIndex + 1) % dataLen;
  myChart.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: currentIndex
  });
  myChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: currentIndex
  });
}, 1000);
ライブ

空白領域のイベントをリッスンする

開発者は、キャンバスの空白領域からトリガーされるイベントをリッスンする必要がある場合があります。たとえば、ユーザーが空白領域をクリックしたときにチャートをリセットする必要がある場合などです。

この機能について説明する前に、zrenderイベントとechartsイベントの2種類のイベントを明確にする必要があります。

myChart.getZr().on('click', function(event) {
  // This listener is listening to a `zrender event`.
});
myChart.on('click', function(event) {
  // This listener is listening to a `echarts event`.
});

zrenderイベントはechartsイベントとは異なります。前者はマウス/ポインタがどこにいてもトリガーされますが、後者はマウス/ポインタがグラフィック要素上にある場合にのみトリガーされます。実際、echartsイベントはzrenderイベントに基づいて実装されています。つまり、zrenderイベントがグラフィック要素でトリガーされると、echartsはechartsイベントをトリガーします。

zrenderイベントを使用すると、次のように空白からのイベントのリッスンを実装できます

myChart.getZr().on('click', function(event) {
  // No "target" means that mouse/pointer is not on
  // any of the graphic elements, which is "blank".
  if (!event.target) {
    // Click on blank. Do something.
  }
});

貢献者 GitHubでこのページを編集する

pissang pissangOvilia Ovilia100pah 100pah