How to access function in Alpine.data

Viewed 25

How to access defined function(s) in Alpine.data() via normal javascript? What I mean the 'normal javascript' is like plain javascript in .js file, console, etc... but not in alpinejs properties

Example:

Alpine.data('utils', () => ({
    func() {
        console.log('Hello, world!')
    }
}))
func() // Doesn't work but works in alpinejs like x-on:click
Alpine.func() // Doesn't work
Alpine.data('utils').func() // Doesn't work
1 Answers

I believe the right way to handle this is via events. So in your external event, you fire an event via dispatchEvent, and on your Alpine app, you listen for the event and respond to it.

So for example, in your custom code:

window.dispatchEvent(new Event('custom-event'))

And in your Alpine:

<div x-data="app" @custom-event.window="doMapStuff()">
Related