imacrayon / alpine-ajax

An Alpine.js plugin for building server-powered frontends.
https://alpine-ajax.js.org
MIT License
666 stars 15 forks source link

$ajax example on website: Why use "@change" on div vs. input? #91

Closed charliesneath closed 1 month ago

charliesneath commented 3 months ago

A simple question regarding this example for using $ajax:

Why is the @change event and associated data attribute attached at the containing div level, vs. the input field level?

As I understand, the onchange event is intended for input, not div.

<div id="email_field" x-data="{email : ''}" @change="$ajax('/validate-email', {
  method: 'post',
  body: { email },
})">
  <label for="email">Email</label>
  <input type="email" name="email" id="email" x-model="email">
</div>
imacrayon commented 2 months ago

Hi, thanks for reaching out,

When there’s a validation error, we have to add an error message and update some attributes on the input, we can easily make both of these changes at once by replacing the parent div. The @change listener on the div works because the change event bubbles up the DOM tree once it is triggered on the input. We could have also attached the listener to the input directly, but personally I think it’s easier to read & maintain when all the Alpine attributes are organized together on one element, instead of spread across two.

imacrayon commented 1 month ago

I'm gonna close this out but feel free to reopen if you have further questions/comments.

charliesneath commented 1 month ago

Yes, thank you for the details here!