Skip to content

Instantly share code, notes, and snippets.

@marcoroth
Last active February 6, 2023 08:20
Show Gist options
  • Save marcoroth/64c308d9e7be047a2061469ebe58daea to your computer and use it in GitHub Desktop.
Save marcoroth/64c308d9e7be047a2061469ebe58daea to your computer and use it in GitHub Desktop.
function addAction(action: string, event: string | undefined = undefined, element: Element = this.element) {
const actions = element.dataset.action.split(" ")
const newAction = event ? `${event}->${this.identifier}#${action}` : `${this.identifier}#${action}`
actions.push(newAction)
element.dataset.action = actions.join(" ")
}
function removeAction(action: string, event: string | undefined = undefined, element: Element = this.element) {
const actions = element.dataset.action.split(" ")
const actionToRemove = actions.find(a => {
if (a.includes("->")) {
const [first, aAction] = a.split("#")
const [aEvent, aIdentifier] = first.split("->")
return aAction === action && aIdentifier === this.identifier && aEvent === event
} else {
const [aIdentifier, aAction] = a.split("#")
return aAction === action && aIdentifier === this.identifier
}
})
element.dataset.action = actions.filter(action => action !== actionToRemove).join(" ")
}
// Usage
this.addAction("myAction") // adds [identifier]#myAction to the controller element
this.addAction("myAction", "click") // adds click->[identifier]#myAction to the controller element
this.addAction("myAction", "click", this.otherTarget) // adds click->[identifier]#myAction to the other target element
this.removeAction("myAction") // removes [identifier]#myAction from the controller element
this.removeAction("myAction", "click") // removes click->[identifier]#myAction from the controller element
this.removeAction("myAction", "click", this.otherTarget) // removes click->[identifier]#myAction from the other target element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment