v0.6.22

Event Binding

Last updated


This page covers wiring DOM events to handlers in the event option with @event.

Syntax


  1. <div id="app">
  2. <button @click="save">Save</button>
  3. <input type="text" @input="typing" />
  4. </div>
  5. <script>
  6. const app = new QUI({
  7. id: "app",
  8. data: { text: "" },
  9. event: {
  10. save: (e) => console.log("saved", app.data.text),
  11. typing: (e) => {
  12. app.data.text = e.target.value;
  13. },
  14. },
  15. });
  16. </script>
Live preview · @pardnchiu/quickui@0.6.22

PrefixExampleDescription
@@clickStandard form
qe-qe-clickEquivalent form

@click="save" becomes element.onclick = app.event.save, and the @click attribute is removed afterwards.

Rules


RuleDescription
Event nameMust be a native event with a matching on* property on the element (click, input, change, submit, keyup and so on); custom events never fire
Handler argumentsOnly the Event; with a function declaration, this is the element
One handler per eventAssigned as a property, so an element keeps only one handler per event
Name lookupThe value is first looked up as a data path and the result is used as the handler name; otherwise the value itself is the name
Unknown nameundefined is assigned; clicking does nothing and no error is raised
:@clickNot supported; the attribute is removed and nothing is bound

Getting the Item Inside a Loop


Handlers do not receive the :for item, so put the identifier in a data-* attribute:
  1. <ul id="app">
  2. <li :for="user in users">
  3. <button :data-id="user.id" @click="remove">Remove {{ user.id }}</button>
  4. </li>
  5. </ul>
  6. <script>
  7. const app = new QUI({
  8. id: "app",
  9. data: { users: [{ id: 1 }, { id: 2 }] },
  10. event: {
  11. remove: (e) => {
  12. const id = +e.target.dataset.id;
  13. app.data.users = app.data.users.filter((u) => u.id !== id);
  14. },
  15. },
  16. });
  17. </script>
Live preview · @pardnchiu/quickui@0.6.22

Using Handlers Outside QuickUI


app.event keeps the original function map, so handlers can be assigned to elements you create yourself:
  1. const button = document.createElement("button");
  2. button.onclick = app.event.save;
  3. app.body.append(button);
中文