Skip to content

Commit

Permalink
Merge pull request #19 from dacook/events
Browse files Browse the repository at this point in the history
Dispatch event when adding new record
  • Loading branch information
guillaumebriday authored Mar 23, 2024
2 parents 079232f + d0ee821 commit 02664cd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
15 changes: 15 additions & 0 deletions spec/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,19 @@ describe('#nestedForm', (): void => {

expect(target.previousElementSibling.innerHTML).toContain('New todo')
})

it('should dispatch events', (): 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 }))
const mockDispatchEvent = jest.spyOn(controllerElement, 'dispatchEvent').mockImplementation(() => true)

addButton.click()

expect(mockDispatchEvent).toHaveBeenCalledWith({
type: 'nested-form:add'
})
})
})
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,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 }))
}

remove (e: Event): void {
Expand Down

0 comments on commit 02664cd

Please sign in to comment.