Skip to content

Commit df52b47

Browse files
committed
feat(listenForBind): automatically call on controller .ownerdocument
1 parent 424468e commit df52b47

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/bind.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export function bind(controller: HTMLElement): void {
1111
listenForBind(controller.shadowRoot)
1212
}
1313
bindElements(controller)
14+
listenForBind(controller.ownerDocument)
1415
}
1516

1617
/**

test/bind.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,30 @@ describe('bind', () => {
138138
expect(instance.foo).to.have.been.called.exactly(2)
139139
})
140140

141+
it('binds elements added to elements subtree', async () => {
142+
const instance = document.createElement('bind-test-element')
143+
chai.spy.on(instance, 'foo')
144+
const el1 = document.createElement('div')
145+
const el2 = document.createElement('div')
146+
el1.setAttribute('data-action', 'click:bind-test-element#foo')
147+
el2.setAttribute('data-action', 'submit:bind-test-element#foo')
148+
document.body.appendChild(instance)
149+
150+
bind(instance)
151+
152+
instance.append(el1, el2)
153+
// We need to wait for a couple of frames after injecting the HTML into to
154+
// controller so that the actions have been bound to the controller.
155+
await waitForNextAnimationFrame()
156+
document.body.removeChild(instance)
157+
158+
expect(instance.foo).to.have.not.been.called()
159+
el1.click()
160+
expect(instance.foo).to.have.been.called.exactly(1)
161+
el2.dispatchEvent(new CustomEvent('submit'))
162+
expect(instance.foo).to.have.been.called.exactly(2)
163+
})
164+
141165
it('can bind elements within the shadowDOM', () => {
142166
const instance = document.createElement('bind-test-element')
143167
chai.spy.on(instance, 'foo')
@@ -199,6 +223,7 @@ describe('bind', () => {
199223
chai.spy.on(instance, 'foo')
200224
root.appendChild(instance)
201225
listenForBind(root).unsubscribe()
226+
listenForBind(document).unsubscribe()
202227
const button = document.createElement('button')
203228
button.setAttribute('data-action', 'click:bind-test-element#foo')
204229
instance.appendChild(button)

0 commit comments

Comments
 (0)