Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AlpineJS (3) magic properties in javascript function

I'm using a store for a modal and like to use the magic $watch method like so:

Alpine.store('modal', {
    init() {
        this.$watch('this.open', (val) => console.log(val))
        // Here I like to do if(open) { document.body.classList.add('overflow-hidden') } 
    },
    open: false,
    id: null,
    close() {
        this.open = false
        this.id = null
    }
})

But I get TypeError: this.$watch is not a function

like image 804
eskimo Avatar asked Sep 07 '25 05:09

eskimo


1 Answers

Wrap the second argument in an arrow function:

Alpine.store('modal', () => ({
    init() {
        this.$watch('this.open', (val) => console.log(val))
    },
    open: false,
    id: null,
    close() {
        this.open = false
        this.id = null
    }
}))

Arrow functions capture the this value of the enclosing context, thus giving you access to Alpine's magic methods.

like image 131
kylepg Avatar answered Sep 10 '25 08:09

kylepg