diff --git a/__tests__/unit/api/chart.spec.ts b/__tests__/unit/api/chart.spec.ts index 7a779aeb7a..ee9d7cf54b 100644 --- a/__tests__/unit/api/chart.spec.ts +++ b/__tests__/unit/api/chart.spec.ts @@ -619,4 +619,41 @@ 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 }, + ], + }); + + // @ts-ignore + expect(chart._hasBindAutoFit).toBe(false); + + await chart.render(); + // @ts-ignore + expect(chart._hasBindAutoFit).toBe(true); + + chart.options({ + autoFit: false, + }); + await chart.render(); + // @ts-ignore + expect(chart._hasBindAutoFit).toBe(false); + }); }); diff --git a/src/api/chart.ts b/src/api/chart.ts index 074fe212a6..b076339522 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,7 +342,15 @@ 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); } } @@ -347,7 +358,8 @@ export class Chart extends View { private _unbindAutoFit() { const options = this.options(); const { autoFit } = options; - if (autoFit) { + if (autoFit || this._hasBindAutoFit) { + this._hasBindAutoFit = false; window.removeEventListener('resize', this._onResize); } }