hybridsjs / hybrids

Extraordinary JavaScript UI framework with unique declarative and functional architecture
https://hybrids.js.org
MIT License
3.04k stars 85 forks source link

Ability to optionally define a custom element #275

Open Hyzual opened 4 hours ago

Hyzual commented 4 hours ago

Hi, again thank you for sharing with us and maintaining hybrids, it's been a great help for us!

We are in a situation where we can sometimes load the code to define the same custom element (for example: tuleap-lazybox-dropdown) twice on the same page. Since the element is defined with the define() function from hybrids, when this happens, it raises the following error:

Uncaught TypeError: Custom element with 'tuleap-lazybox-dropdown' tag name already defined outside of the hybrids context

The error is definitely useful, but in our case the element is really the same one, so it is okay to just "not re-define it". We can use the following code to achieve that:

const TAG = "tuleap-lazybox-dropdown";
const MyElement = define.compile({ <element definition object...> });

if (!window.customElements.get(TAG)) {
    window.customElements.define(TAG, MyElement);
}

Do you think, as a feature request, we could maybe use another function or option from hybrids to have this behavior, to define an element unless its tag name is already in the customElements registry ? Maybe something like define.optional({ <element definition object...> }). What do you think about it ?

smalluban commented 3 hours ago

Is it the use case where you import files that define elements more than once on the same page?

Hyzual commented 3 hours ago

Yes, we have "internal libraries" that define elements, and they can end up being used in several bundled JS files that are loaded on the same page.