yysun / apprun

AppRun is a JavaScript library for developing high-performance and reliable web applications using the elm inspired architecture, events and components.
https://apprun.js.org
MIT License
1.18k stars 57 forks source link

How to avoid triggering components initial event handler on form submit? #104

Closed jkleiser closed 4 years ago

jkleiser commented 4 years ago

In the "Remote" component in my new SPA I have this form:

<form onsubmit={e => app.run("@get-host-games", state.host)}>
  <input type="text" autocapitalize="off" $bind="host" />
  <button class="btn">Get Games</button>
</form>

In the update list I also have this event handler:

"#Remote": (state, token) => {
  console.log("#Remote, token=%s", token);
  if (state.host.length > 0) {
    app.run("@get-host-games", state.host);
  }
  return { ...state, token };
}

When I enter something in the form's input and click the button, I see in the console that the "#Remote" event handler is also being called. The effect is that app.run("@get-host-games", state.host) is executed twice. It is not a big problem, but can I avoid the automatic call to the "#Remote" event handler in this situation?

Is it my use of onsubmit that triggers the "#Remote" event handler?

yysun commented 4 years ago

You can pass e to the event handler:

<form onsubmit={e => app.run("@get-host-games", state.host, e)}>
  ......
</form>

and then cancel it:

"#Remote": (state, token, e) => {
  e.preventDefault();
  ......
}
jkleiser commented 4 years ago

This is probably what you had in mind:

<form onsubmit={e => { e.preventDefault(); app.run("@get-host-games", state.host); }}>

It does what I wanted. The added e in "#Remote": (state, token, e) => { seems always to be undefined. Thanks.