Skip to content

Commit

Permalink
Improvements to Stimulus automatic event handling (#526)
Browse files Browse the repository at this point in the history
  • Loading branch information
spohlenz authored Dec 4, 2024
1 parent 350f6d6 commit 0e112ec
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
2 changes: 1 addition & 1 deletion app/assets/bundle/trestle/admin.js

Large diffs are not rendered by default.

26 changes: 23 additions & 3 deletions frontend/js/controllers/application_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,21 @@ import { Controller } from '@hotwired/stimulus'
import { fetchWithErrorHandling, fetchTurboStream } from '../core/fetch'

export default class extends Controller {
appendAction (event, action, element = this.element) {
const actions = element.dataset.action ? element.dataset.action.split(' ') : []
actions.push(`${event}->${this.identifier}#${action}`)
appendAction (event, method, element = this.element) {
const actions = this.actionsList(element)
const newAction = `${event}->${this.identifier}#${method}`

if (!actions.includes(newAction)) {
actions.push(newAction)
}

element.dataset.action = actions.join(' ')
}

removeAction (event, method, element = this.element) {
const newAction = `${event}->${this.identifier}#${method}`
const actions = this.actionsList(element).filter(action => action !== newAction)

element.dataset.action = actions.join(' ')
}

Expand All @@ -17,6 +29,14 @@ export default class extends Controller {
return fetchTurboStream(url, options)
}

actionsList (element) {
if (element.dataset.action) {
return element.dataset.action.split(' ')
} else {
return []
}
}

get csrfToken () {
return document.querySelector("[name='csrf-token']").content
}
Expand Down

0 comments on commit 0e112ec

Please sign in to comment.