From f1cbab276efdf64c6505b46b75db0689819ee1d7 Mon Sep 17 00:00:00 2001 From: Christoph Reiter <reiter.christoph@gmail.com> Date: Thu, 16 Apr 2020 14:16:31 +0200 Subject: [PATCH] Allow calling defineCustomElement multiple times with the same element In case we try to register the element multiple times under the same name just do nothing. This allows us to not register things by default and register under the same name in multiple places where needed without coordination. --- packages/common/test/unit.js | 9 +++++++++ packages/common/utils.js | 4 ++++ 2 files changed, 13 insertions(+) diff --git a/packages/common/test/unit.js b/packages/common/test/unit.js index 171b402c..e444d46d 100644 --- a/packages/common/test/unit.js +++ b/packages/common/test/unit.js @@ -27,6 +27,15 @@ suite('utils', () => { expect(node.foo).to.equal(42); }); + test('defineCustomElement multiple times', () => { + class SomeElement2 extends HTMLElement { + } + let res = utils.defineCustomElement("test-some-element-2", SomeElement2); + assert.isTrue(res); + res = utils.defineCustomElement("test-some-element-2", SomeElement2); + assert.isTrue(res); + }); + test('getAPiUrl', () => { assert(utils.getAPiUrl().startsWith("http")); }); diff --git a/packages/common/utils.js b/packages/common/utils.js index d6e8753c..a0d3c469 100644 --- a/packages/common/utils.js +++ b/packages/common/utils.js @@ -103,6 +103,10 @@ export const base64EncodeUnicode = (str) => { * @param {object} options */ export const defineCustomElement = (name, constructor, options) => { + // In case the constructor is already defined just do nothing + if (customElements.get(name) === constructor) { + return true; + } // Checks taken from https://github.com/webcomponents/webcomponentsjs/blob/master/webcomponents-loader.js if (!('attachShadow' in Element.prototype && 'getRootNode' in Element.prototype && window.customElements)) { var elements = document.getElementsByTagName(name); -- GitLab