Skip to content

Commit 9d6366d

Browse files
keithamuskoddsson
andcommitted
fix: ensure shadowRoot is bound after connectedcallback
This adds a test and ensures bind is called on shadowroots created after custom `connectedCallback` behavior. Co-authored-by: Kristján Oddsson <koddsson@gmail.com>
1 parent bffc528 commit 9d6366d

3 files changed

Lines changed: 28 additions & 5 deletions

File tree

src/bind.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@ const controllers = new WeakSet<Element>()
66
*/
77
export function bind(controller: HTMLElement): void {
88
controllers.add(controller)
9-
if (controller.shadowRoot) {
10-
bindElements(controller.shadowRoot)
11-
listenForBind(controller.shadowRoot)
12-
}
9+
if (controller.shadowRoot) bindShadow(controller.shadowRoot)
1310
bindElements(controller)
1411
listenForBind(controller.ownerDocument)
1512
}
1613

14+
export function bindShadow(root: ShadowRoot): void {
15+
bindElements(root)
16+
listenForBind(root)
17+
}
18+
1719
const observers = new WeakMap<Node, Subscription>()
1820
/**
1921
* Set up observer that will make sure any actions that are dynamically

src/controller.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {register} from './register.js'
2-
import {bind} from './bind.js'
2+
import {bind, bindShadow} from './bind.js'
33
import {autoShadowRoot} from './auto-shadow-root.js'
44
import {defineObservedAttributes, initializeAttrs} from './attr.js'
55
import type {CustomElement} from './custom-element.js'
@@ -18,6 +18,7 @@ export function controller(classObject: CustomElement): void {
1818
initializeAttrs(this)
1919
bind(this)
2020
if (connect) connect.call(this)
21+
if (this.shadowRoot) bindShadow(this.shadowRoot)
2122
}
2223
defineObservedAttributes(classObject)
2324
register(classObject)

test/controller.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,24 @@ describe('controller', () => {
3737

3838
expect(instance.foo).to.have.been.called(1)
3939
})
40+
41+
it('binds shadowRoots after connectedCallback behaviour', async () => {
42+
controller(
43+
class ControllerBindShadowElement extends HTMLElement {
44+
connectedCallback() {
45+
this.attachShadow({mode: 'open'})
46+
const button = document.createElement('button')
47+
button.setAttribute('data-action', 'click:controller-bind-shadow#foo')
48+
this.shadowRoot.appendChild(button)
49+
}
50+
}
51+
)
52+
const instance = document.createElement('controller-bind-shadow')
53+
chai.spy.on(instance, 'foo')
54+
document.body.appendChild(instance)
55+
56+
instance.shadowRoot.querySelector('button').click()
57+
58+
expect(instance.foo).to.have.been.called(1)
59+
})
4060
})

0 commit comments

Comments
 (0)