visioncode
visioncode

Reputation: 97

Access properties from a function inside Alpine JS

I try to use some of my jQuery plugins within Alpine (of course Alpine should replace jQuery in long-term). This autocomplete plugin theoretically works as expected, but I can't set the targetCustomerId from within the onSelect(). How can I access and change the values of my object properties from inside the autocomplete functions?

x-data="
        postForm($el.id, 'contracts/add', {
            targetCustomerId: '<?=$customer->CUSTOMERID;?>',

            init() {
                customerInput = $($refs.autocompleteInput).autocomplete({
                    type: 'POST',
                    serviceUrl: 'api/getCustomers',
                    onSearchStart: function() {
                        $(this).addClass('input-loader')
                    },
                    onSearchComplete: function() {
                        $(this).removeClass('input-loader')
                    },
                    onSearchError: function() {
                        $(this).removeClass('input-loader')
                    },
                    onSelect: function (suggestion) {
                        this.targetCustomerId = suggestion.value;
                    }
                });
            }
        })
    "

The postForm() is simplified just something like this:

function postForm(formId, url, objSettings) {
    var defaults = {
        form: document.getElementById(formId),
        formData: '',
        message: '',
        isLoading: false
    }

    return {...defaults, ...objSettings};
}

Upvotes: 0

Views: 1632

Answers (1)

Dauros
Dauros

Reputation: 10577

According to https://github.com/devbridge/jQuery-Autocomplete's documentation, inside the onSelect method, the this variable refers the input element so we cannot access Alpine.js context like this, we have to use e.g. $data magic.

Assuming the response data looks like this:

{
    "suggestions": [
        { "value": "Customer 1", "data": 1 },
        { "value": "Customer 2", "data": 2 }
    ]
}

So the data refers to CustomerId not the value field, the modified onSelect method:

onSelect: function (suggestion) {
    $data.targetCustomerId = suggestion.data;
}

Here $data refers to Alpine.js data object, and suggestion is the clicked autocomplete item.

Upvotes: 2

Related Questions