事件與動作

使用者可以透過其操作觸發對應的事件。開發人員可以透過監聽這些事件來處理回調函數,例如跳轉到新的網站、彈出對話框或向下鑽取資料。

事件的名稱和 DOM 事件都是小寫字串。以下是一個綁定監聽 click 事件的範例。

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

ECharts 中有兩種事件,一種是當使用者點擊滑鼠或將滑鼠懸停在圖表中的元素上時發生,另一種是當使用者觸發某些互動動作時發生。例如,當變更圖例選取時會觸發 '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);

query 可以是 stringObject

如果是 string,格式可以是 mainTypemainType.subType,例如

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

如果是 Objectquery 可以包含多個屬性

{
  ${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 中的所有元件互動都會觸發對應的事件。 events 文件中列出了常見的事件和參數。

以下是一個監聽圖例事件的範例

// 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: '' }) 用於觸發行為。這管理所有動作,並且可以方便地記錄行為。

action 中列出了常用的行為和對應的參數。

以下範例示範如何使用 dispatchAction 逐一醒目顯示圓餅圖中的每個扇區。

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 事件。

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