从 Alpine JS 中的函数访问属性

Access properties from a function inside Alpine JS

我尝试在 Alpine 中使用我的一些 jQuery 插件(当然 Alpine 应该长期取代 jQuery)。这个自动完成插件理论上可以按预期工作,但我无法从 onSelect() 中设置 targetCustomerId。如何从自动完成函数内部访问和更改我的对象属性的值?

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;
                    }
                });
            }
        })
    "

postForm() 被简化成这样:

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

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

根据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

假设响应数据如下所示:

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

所以 data 指的是 CustomerId 而不是 value 字段,修改后的 onSelect 方法:

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

这里$data指的是Alpine.js数据对象,suggestion是点击的自动补全项