简体   繁体   中英

Javascript: Invoke function directly or dispatch event?

Where we have js code that submits a form instead of just submitting the form like:

form.submit();

Should we instead dispatch a (bubbling, cancelable) event in order to allow other potential js event listeners the chance to handle the form submission:

form.dispatchEvent(new Event('submit', {bubbles: true, cancelable: true}));

It seems like this allows our code to play more nicely with others. If this is true, why isn't this pattern pushed more?

HTMLFormElement.requestSubmit() to the rescue!

In most cases in which a form is to be submitted programmatically via JavaScript, it's wise to use requestSubmit() rather than submit() . Doing so ensures submit handlers will have a chance to handle the submit event. Use submit() only when you want to explicitly submit the form ignoring any registered submit event listeners and form validation.

I was simply not aware of this newer form method.

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

The HTMLFormElement.submit() method submits a given <form> .

This method is similar, but not identical to, activating a form's submit <button> . When invoking this method directly, however:

  • No submit event is raised. In particular, the form's onsubmit event handler is not run.
  • Constraint validation is not triggered.

The HTMLFormElement.requestSubmit() method is identical to activating a form's submit <button> and does not have these differences.

And usage notes from https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit

The obvious question is: Why does this method [ requestSubmit() ] exist, when we've had the submit() method since the dawn of time?

The answer is simple. submit() submits the form, but that's all it does. requestSubmit() , on the other hand, acts as if a submit button were clicked. The form's content is validated, and the form is submitted only if validation succeeds. Once the form has been submitted, the submit event is sent back to the form object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM