Created
October 5, 2021 15:45
-
-
Save brenogazzola/6be19aa88088fe1e25e740ad234d1706 to your computer and use it in GitHub Desktop.
Stimulus Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from 'stimulus' | |
export default class extends Controller { | |
// ============================================================================ | |
// Public | |
// ============================================================================ | |
/* | |
* Removes an element from the DOM | |
*/ | |
remove (event) { | |
const target = event.currentTarget.dataset.remove || 'this' | |
this.chooseTarget(event.currentTarget, target).remove() | |
} | |
/* | |
* Toggles the specified attribute of the target | |
*/ | |
toggleAttribute (event) { | |
const target = event.currentTarget.dataset.target | |
const attribute = event.currentTarget.dataset.attribute || 'disabled' | |
target.split(',').forEach(target => { | |
this.chooseTarget(event.currentTarget, target).toggleAttribute(attribute) | |
}) | |
} | |
/* | |
* Toggles the specified class of the target | |
*/ | |
toggleClass (event) { | |
const target = event.currentTarget.dataset.target | |
const klass = element.dataset.class || 'hidden' | |
target.split(',').forEach(target => { | |
this.chooseTarget(event.currentTarget, target).toggle(klass) | |
}) | |
} | |
// ============================================================================ | |
// Private | |
// ============================================================================ | |
chooseTarget (element, target) { | |
target = target.trim() | |
if (!target) { | |
return element | |
} else if (target === 'parent') { | |
return element.parentElement | |
} else if (target === 'this') { | |
return element | |
} else if (target.indexOf('closest') !== -1) { | |
return element.closest(target.split(' ')[1]) | |
} else { | |
return document.querySelector(target) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment