From 06bca8f811b33251c3e99b880fb4c7cb57886ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B4=9D=E5=93=B2?= Date: Fri, 5 May 2023 11:12:20 +0800 Subject: [PATCH] feat: chart bind autoFit in render --- __tests__/unit/api/chart.spec.ts | 34 ++++++++++++++++++++++++++++++++ src/api/chart.ts | 18 +++++++++++++---- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/__tests__/unit/api/chart.spec.ts b/__tests__/unit/api/chart.spec.ts index 7a779aeb7a..c95f3b0b03 100644 --- a/__tests__/unit/api/chart.spec.ts +++ b/__tests__/unit/api/chart.spec.ts @@ -619,4 +619,38 @@ describe('Chart', () => { expect(chart.width()).toBeUndefined(); expect(chart.height()).toBeUndefined(); }); + + it('chart.options({ autoFit: true }) should bind autoFit.', async () => { + const div = document.createElement('div'); + const chart = new Chart({ + container: div, + }); + chart.options({ + autoFit: true, + theme: 'classic', + type: 'interval', + encode: { + x: 'genre', + y: 'sold', + }, + data: [ + { genre: 'Sports', sold: 275 }, + { genre: 'Strategy', sold: 115 }, + { genre: 'Action', sold: 120 }, + { genre: 'Shooter', sold: 350 }, + { genre: 'Other', sold: 150 }, + ], + }); + + expect(chart['_hasBindAutoFit']).toBe(false); + + await chart.render(); + expect(chart['_hasBindAutoFit']).toBe(true); + + chart.options({ + autoFit: false, + }); + await chart.render(); + expect(chart['_hasBindAutoFit']).toBe(false); + }); }); diff --git a/src/api/chart.ts b/src/api/chart.ts index 074fe212a6..4456e40508 100644 --- a/src/api/chart.ts +++ b/src/api/chart.ts @@ -178,6 +178,8 @@ export class Chart extends View { private _options: G2ViewTree; private _width: number; private _height: number; + // Identifies whether bindAutoFit. + private _hasBindAutoFit = false; constructor(options: ChartOptions) { const { container, canvas, ...rest } = options || {}; @@ -185,10 +187,11 @@ export class Chart extends View { this._container = normalizeContainer(container); this._emitter = new EventEmitter(); this._context = { library, emitter: this._emitter, canvas }; - this._bindAutoFit(); } render(): Promise { + this._bindAutoFit(); + if (!this._context.canvas) { // Init width and height. const { renderer, plugins } = this.options(); @@ -339,15 +342,22 @@ export class Chart extends View { private _bindAutoFit() { const options = this.options(); const { autoFit } = options; + + if (this._hasBindAutoFit) { + // If it was bind before, unbind it now. + if (!autoFit) this._unbindAutoFit(); + return; + } + if (autoFit) { + this._hasBindAutoFit = true; window.addEventListener('resize', this._onResize); } } private _unbindAutoFit() { - const options = this.options(); - const { autoFit } = options; - if (autoFit) { + if (this._hasBindAutoFit) { + this._hasBindAutoFit = false; window.removeEventListener('resize', this._onResize); } }