Created
August 2, 2025 08:26
-
-
Save Jipok/319ed2cc68de84c652a5e63b0bb408cf to your computer and use it in GitHub Desktop.
j-click.js
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
document.addEventListener('alpine:init', () => { | |
let isGlobalListenerAttached = false; | |
const globalJClickHandler = (event) => { | |
let target = event.target; | |
const clickedElement = target.closest('[j-click]'); | |
if (!clickedElement) { | |
return; | |
} | |
const alpineComponentRoot = Alpine.findClosest(clickedElement, el => el._x_dataStack); | |
if (!alpineComponentRoot) { | |
console.warn('j-click: Could not find parent Alpine component.', clickedElement); | |
return; | |
} | |
const expressionToEvaluate = clickedElement.getAttribute('j-click'); | |
Alpine.evaluate(alpineComponentRoot, expressionToEvaluate, { | |
scope: { | |
'$event': event | |
} | |
}); | |
}; | |
if (!isGlobalListenerAttached) { | |
document.addEventListener('click', globalJClickHandler, true); | |
isGlobalListenerAttached = true; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment