Skip to content

Commit

Permalink
Dispatch events
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaumebriday committed Mar 23, 2024
1 parent 02664cd commit 59f77a9
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Dispatch `rails-nested-form:add` and `rails-nested-form:remove` events.

## [4.1.0] - 2022-12-23

### Added
Expand Down
9 changes: 6 additions & 3 deletions spec/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,17 @@ describe('#nestedForm', (): void => {
const controllerElement: HTMLButtonElement = document.querySelector("[data-controller='nested-form']")
const addButton: HTMLButtonElement = document.querySelector("[data-action='nested-form#add']")

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

addButton.click()

expect(mockDispatchEvent).toHaveBeenCalledWith({
type: 'nested-form:add'
type: 'rails-nested-form:add',
eventInit: {
bubbles: true
}
})
})
})
6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ export default class extends Controller {
const content: string = this.templateTarget.innerHTML.replace(/NEW_RECORD/g, new Date().getTime().toString())
this.targetTarget.insertAdjacentHTML('beforebegin', content)

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

remove (e: Event): void {
Expand All @@ -36,5 +37,8 @@ export default class extends Controller {
const input: HTMLInputElement = wrapper.querySelector("input[name*='_destroy']")
input.value = '1'
}

const event = new CustomEvent('rails-nested-form:remove', { bubbles: true })
this.element.dispatchEvent(event)
}
}

0 comments on commit 59f77a9

Please sign in to comment.