Skip to content

Commit

Permalink
feat(event): add plot events bind (#1412)
Browse files Browse the repository at this point in the history
* feat(event): add plot events bind

* test(event): add test cases & type define

* fix(core): fix by prettier
  • Loading branch information
hustcc authored and BBSQQ committed Aug 25, 2020
1 parent 05afca6 commit 3575f73
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
38 changes: 38 additions & 0 deletions __tests__/unit/core/index-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,42 @@ describe('core', () => {

expect(line.chart.getTheme().colors10).toEqual(['green']);
});

it('event', async () => {
const line = new Line(createDiv(), {
width: 400,
height: 300,
appendPadding: 10,
data: partySupport.filter((o) => ['FF', 'Lab'].includes(o.type)),
xField: 'date',
yField: 'value',
seriesField: 'type',
theme: {
colors10: ['red'],
},
});

line.render();

function click(): Promise<Event> {
return new Promise((resolve, reject) => {
line.on('element:click', (e) => {
resolve(e);
});

line.chart.emit('element:click', {
_data: 1,
type: 'element:click',
});
});
}

const e = await click();

// 直接接受 G2 透传的事件
expect(e).toEqual({
type: 'element:click',
_data: 1,
});
});
});
27 changes: 23 additions & 4 deletions src/core/plot.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Chart } from '@antv/g2';
import { Chart, Event } from '@antv/g2';
import { deepMix } from '@antv/util';
import EE from '@antv/event-emitter';
import { bind } from 'size-sensor';
import { Adaptor } from './adaptor';
import { ChartOptions, Data } from '../types';

/**
* 所有 plot 的基类
*/
export abstract class Plot<O extends ChartOptions> {
export abstract class Plot<O extends ChartOptions> extends EE {
/** plot 类型名称 */
public abstract readonly type: string = 'base';
/** plot 的 schema 配置 */
Expand All @@ -20,11 +21,14 @@ export abstract class Plot<O extends ChartOptions> {
private unbind: () => void;

constructor(container: string | HTMLElement, options: O) {
super();
this.container = typeof container === 'string' ? document.getElementById(container) : container;
const defaultOptions = this.getDefaultOptions();
this.options = deepMix({}, defaultOptions, options);

this.options = deepMix({}, this.getDefaultOptions(), options);

this.createG2();

this.bindEvents();
}

/**
Expand All @@ -46,6 +50,19 @@ export abstract class Plot<O extends ChartOptions> {
});
}

/**
* 绑定代理所有 G2 的事件
*/
private bindEvents() {
if (this.chart) {
this.chart.on('*', (e: Event) => {
if (e?.type) {
this.emit(e.type, e);
}
});
}
}

/**
* 获取默认的 options 配置项
* 每个组件都可以复写
Expand Down Expand Up @@ -116,6 +133,8 @@ export abstract class Plot<O extends ChartOptions> {
this.unbindSizeSensor();
// G2 的销毁
this.chart.destroy();
// 清空已经绑定的事件
this.off();
}

/**
Expand Down

0 comments on commit 3575f73

Please sign in to comment.