I'm trying to move some inline alpine.js to an external JavaScript file, with the thought of being able to manipulate the state of for example a modal after a form submit with ajax.
So my modal with tailwind:
<div x-data="showFileModal" class="inline-block">
<button type="button" @click="toggle">{{ __('Open Model') }}</button>
<div x-show="openFileModal" class="flex fixed overflow-auto z-10 top-O right-0 bottom-0 left-0">
<div x-show="openFileModal" class="w-2/5 p-5 mx-auto" @click.away="toggle">
<form action="" method="">
<button id="form-submit" type="submit">{{ __('Submit') }}</button>
</form>
</div>
</div>
</div>
My external JavaScript file:
window.showFileModal = () => {
return {
openFileModal: false,
toggle() {
this.openFileModal = ! this.openFileModal;
}
}
};
$('#form-submit').click(function (e)
{
e.preventDefault();
$.ajax({
success: function (s)
{
showFileModal().toggle();
}
})
});
The toggle function on the button to open and close the model works, but trying to call it inside the ajax success function is not working. Even if i try it on a normal button without any ajax logic it also doesn't work. I either get no error in the console, or i get an error that toggle isn't a function if i try with a variation of using 'this'.
How can i call upon that toggle function outside of the showFileModal function?
This happens most likely because your showFileModal module is not available where you're calling it. You're also mixing Alpine.js with JQuery, which shouldn't be necessary.
I'd suggest something like this:
<div x-data="showFileModal" class="inline-block">
<button type="button" @click="toggle">{{ __('Open Model') }}</button>
<div x-show="openFileModal" class="flex fixed overflow-auto z-10 top-O right-0 bottom-0 left-0">
<div x-show="openFileModal" class="w-2/5 p-5 mx-auto" @click.away="toggle">
<form action="" method="">
<button type="submit"
@click.prevent="submitForm()">
{{ __('Submit') }}
</button>
</form>
</div>
</div>
And in your JS you'd have to declare the function like
window.showFileModal = () => {
return {
openFileModal: false,
toggle() { .. },
submitForm(event) {
// do your API request here
}
}
};