Skip to content

Commit

Permalink
fixed #20
Browse files Browse the repository at this point in the history
  • Loading branch information
GianlucaGuarini committed Nov 2, 2024
1 parent 1f54abf commit 9d38df7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
})

Expand All @@ -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
Expand Down
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('<p><!----></p>', []),
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')
})
})

0 comments on commit 9d38df7

Please sign in to comment.