Skip to content

Commit 819ee81

Browse files
committed
Dispatch event when adding new record
The controller element is the target of the event. We don't need `CustomEvent`, because there's no custom data to pass.
1 parent 079232f commit 819ee81

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

spec/index.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,18 @@ describe('#nestedForm', (): void => {
4343

4444
expect(target.previousElementSibling.innerHTML).toContain('New todo')
4545
})
46+
47+
it('should dispatch events', (): void => {
48+
const controllerElement: HTMLButtonElement = document.querySelector("[data-controller='nested-form']")
49+
const addButton: HTMLButtonElement = document.querySelector("[data-action='nested-form#add']")
50+
51+
jest.spyOn(global, 'Event').mockImplementation((type: string, eventInit?: any) => ({ type, eventInit }))
52+
const mockDispatchEvent = jest.spyOn(controllerElement, 'dispatchEvent').mockImplementation(() => true)
53+
54+
addButton.click()
55+
56+
expect(mockDispatchEvent).toHaveBeenCalledWith({
57+
type: 'nested-form:add'
58+
})
59+
})
4660
})

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ export default class extends Controller {
1818

1919
const content: string = this.templateTarget.innerHTML.replace(/NEW_RECORD/g, new Date().getTime().toString())
2020
this.targetTarget.insertAdjacentHTML('beforebegin', content)
21+
22+
this.element.dispatchEvent(new Event('nested-form:add', { bubbles: true }))
2123
}
2224

2325
remove (e: Event): void {

0 commit comments

Comments
 (0)