Created
February 27, 2024 18:30
-
-
Save mattvague/9997a1106aaf66e7dcdd21044cc573e4 to your computer and use it in GitHub Desktop.
Example of Alpine.js data clashes
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Alpine.js Example</title> | |
<script> | |
document.addEventListener('alpine:init', () => { | |
Alpine.directive('modal', ($el) => { | |
Alpine.bind($el, { | |
"x-data"() { | |
return { | |
__isOpen: true | |
} | |
}, | |
"x-show": '__isOpen' | |
}); | |
}) | |
Alpine.magic('modal', ($el) => { | |
const $data = Alpine.$data($el) | |
return { | |
get isOpen() { return $data.__isOpen }, | |
set isOpen(open) { $data.__isOpen = open } | |
} | |
}) | |
Alpine.directive('disclosure', ($el) => { | |
Alpine.bind($el, { | |
"x-data"() { | |
return { | |
__isOpen: true | |
} | |
}, | |
"x-show": '__isOpen' | |
}); | |
}) | |
Alpine.magic('disclosure', ($el) => { | |
const $data = Alpine.$data($el) | |
return { | |
get isOpen() { return $data.__isOpen }, | |
set isOpen(open) { $data.__isOpen = open } | |
} | |
}) | |
}) | |
</script> | |
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script> | |
</head> | |
<body> | |
<div x-data x-modal> | |
My Modal! | |
<button @click="$modal.isOpen = false">Close Modal 1</button> | |
<div x-disclosure> | |
<button @click="$modal.isOpen = false">Close Modal 2</button> | |
<button @click="$disclosure.isOpen = false">Close Disclosure</button> | |
</div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment