From cf4ea6a8e71bccad08ac9f058f4eb588f370414a Mon Sep 17 00:00:00 2001 From: Guido Bouman Date: Sat, 14 Apr 2018 12:26:38 +0200 Subject: [PATCH] fix: Prevent duplicate PanelSnap instances on the same container --- src/panelSnap.js | 4 ++++ src/panelSnap.test.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/panelSnap.js b/src/panelSnap.js index 33bcc74..a2ca20f 100644 --- a/src/panelSnap.js +++ b/src/panelSnap.js @@ -28,9 +28,13 @@ export default class PanelSnap { }; this.container = this.options.container; + if (this.container.dataset.panelsnapId) { + throw new Error('PanelSnap is already initialised on this container, aborting.'); + } INSTANCE_COUNTER += 1; this.instanceIndex = INSTANCE_COUNTER; + this.container.dataset.panelsnapId = this.instanceIndex; this.scrollingContainer = getScrollingElement(this.container); this.panelList = document.querySelectorAll(`[data-panelsnap-id="${this.instanceIndex}"] ${this.options.panelSelector}`); diff --git a/src/panelSnap.test.js b/src/panelSnap.test.js index 72155e0..3699c49 100644 --- a/src/panelSnap.test.js +++ b/src/panelSnap.test.js @@ -5,4 +5,18 @@ describe('Constructor', () => { const instance = new PanelSnap(); expect(instance).toBeInstanceOf(PanelSnap); }); + + test('prevents duplicate init of panelSnap on the same element', () => { + const container = document.createElement('div'); + // eslint-disable-next-line no-unused-vars + const firstInstance = new PanelSnap({ container }); + expect(() => new PanelSnap({ container })).toThrow('already initialised'); + }); + + test('prevents duplicate init of panelSnap on the same element', () => { + const container = document.createElement('div'); + // eslint-disable-next-line no-unused-vars + const firstInstance = new PanelSnap({ container }); + expect(() => new PanelSnap({ container })).toThrow('already initialised'); + }); });