How to access properties into watch method in AlpineJS?

54 views Asked by At

I want to access the properties of the component inside the watch method but it's not working. Apparently, this is not defined. I use AlpineJS 3

Here my code :

<form x-data="config()" x-init="initModule()">
<input type="radio" value="one_date" x-model="type_date" /> 
<label >Option A</label>
                        

<input type="radio"  value="multi_date" x-model="type_date"/> 
<label  >Option B</label>
</form>

<script>
 function config(){
        return {
            type_date : '',
            date_option : {dateFormat: "d-m-Y"},
            initModule(){
                
                this.$watch('type_date', function(value){
                    console.log(this.date_option)
                 });
        }
}                   
                  
</script>

It's what i get in the console : undefined

1

There are 1 answers

0
Pippo On BEST ANSWER

The problem is that when you enter the anonymous function passed to $watch, the context changes and "this" refers to the window object (you can check this thing by adding a console.log(this); in the function).
To get around the problem we can use an arrow function which does not have its own context, so "this" will refer to the container object.

From Alpine 3, by adding an init() function to the object, you will no longer need to specify an x-init attribute: the init() function, if present, will be called automatically.

<form x-data="config()">

    <label>
        <input type="radio" value="one_date" x-model="type_date" />
        Option A
    </label>


    <label>
        <input type="radio" value="multi_date" x-model="type_date"/>
        Option B
    </label>

</form>

<script>

    function config() {

        return {

            type_date: "",

            date_option: {dateFormat: "d-m-Y"},

            init() {

                this.$watch("type_date", (value) => {
                    console.log(this.date_option);
                });
            }
        };
    }

</script>