From 9d38df7746b3dd5d0fd64967a982d0244c0bf9b0 Mon Sep 17 00:00:00 2001 From: Gianluca Guarini Date: Sun, 3 Nov 2024 00:05:22 +0100 Subject: [PATCH] fixed #20 --- src/index.js | 10 ++++++++-- test.js | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index d55480f..005a905 100644 --- a/src/index.js +++ b/src/index.js @@ -33,7 +33,7 @@ function moveChildren(source, target) { */ export function createElementClass(api) { const { css, exports, template } = api - + const originalOnMounted = exports?.onMounted ?? (() => {}) const tagImplementation = exports || {} return class extends HTMLElement { @@ -43,7 +43,7 @@ export function createElementClass(api) { // create the shadow DOM this.shadow = this.attachShadow({ mode: 'open' }) this.componentFactory = component({ - exports: tagImplementation, + exports: { ...tagImplementation, onMounted: undefined }, template, }) @@ -57,6 +57,12 @@ export function createElementClass(api) { // move the tag root html into the shadow DOM moveChildren(this.component.root, this.shadow) + + // call the onmounted only when the DOM has been moved + originalOnMounted.apply(this.component, [ + this.component.props, + this.component.state, + ]) } // on attribute changed diff --git a/test.js b/test.js index 8fbda72..55fb795 100644 --- a/test.js +++ b/test.js @@ -153,4 +153,21 @@ describe('@riotjs/custom-elements', function () { '10px', ) }) + + it('the shadow root is accessible on the onmounted event (issue https://github.com/riot/custom-elements/issues/20)', () => { + const name = tmpTagName() + define(name, { + template: (t) => t('

', []), + exports: { + onMounted() { + console.log(this) + this.root.shadowRoot.querySelector('p').textContent = 'foo' + }, + }, + }) + + const el = document.createElement(name) + document.body.appendChild(el) + expect(el.shadowRoot.querySelector('p').textContent).to.be.equal('foo') + }) })