Skip to content

Commit 59f77a9

Browse files
Dispatch events
1 parent 02664cd commit 59f77a9

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88

9+
### Added
10+
11+
- Dispatch `rails-nested-form:add` and `rails-nested-form:remove` events.
12+
913
## [4.1.0] - 2022-12-23
1014

1115
### Added

spec/index.test.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,17 @@ describe('#nestedForm', (): void => {
4848
const controllerElement: HTMLButtonElement = document.querySelector("[data-controller='nested-form']")
4949
const addButton: HTMLButtonElement = document.querySelector("[data-action='nested-form#add']")
5050

51-
// @ts-ignore following line
52-
jest.spyOn(global, 'Event').mockImplementation((type: string, eventInit?: any) => ({ type, eventInit }))
51+
// @ts-ignore
52+
jest.spyOn(global, 'CustomEvent').mockImplementation((type: string, eventInit?: any) => ({ type, eventInit }))
5353
const mockDispatchEvent = jest.spyOn(controllerElement, 'dispatchEvent').mockImplementation(() => true)
5454

5555
addButton.click()
5656

5757
expect(mockDispatchEvent).toHaveBeenCalledWith({
58-
type: 'nested-form:add'
58+
type: 'rails-nested-form:add',
59+
eventInit: {
60+
bubbles: true
61+
}
5962
})
6063
})
6164
})

src/index.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ export default class extends Controller {
1919
const content: string = this.templateTarget.innerHTML.replace(/NEW_RECORD/g, new Date().getTime().toString())
2020
this.targetTarget.insertAdjacentHTML('beforebegin', content)
2121

22-
this.element.dispatchEvent(new Event('nested-form:add', { bubbles: true }))
22+
const event = new CustomEvent('rails-nested-form:add', { bubbles: true })
23+
this.element.dispatchEvent(event)
2324
}
2425

2526
remove (e: Event): void {
@@ -36,5 +37,8 @@ export default class extends Controller {
3637
const input: HTMLInputElement = wrapper.querySelector("input[name*='_destroy']")
3738
input.value = '1'
3839
}
40+
41+
const event = new CustomEvent('rails-nested-form:remove', { bubbles: true })
42+
this.element.dispatchEvent(event)
3943
}
4044
}

0 commit comments

Comments
 (0)