@@ -4,26 +4,42 @@ import { debounce } from "../lib/debounce";
44/**
55 * This element submits a form automatically clicking on a hidden submit input/button
66 *
7- * The form gets submitted on each change, or on input with a debounce.
7+ * The form gets submitted on each change or input with a configurable debounce.
88 * You still need to make sure that this is what the user expects and/or that the submit is captured
99 * and only part of the DOM get's updated using a technique like turbo frames.
1010 * (We don't use `form.submit()` since that event isn't captured by turbo)
11+ *
12+ * The debounce for the change or input event can be configured with `data-change-debounce`
13+ * or `data-input-debounce`. This value is only picked up when the component is connected
14+ * any later changes to this attribute are ignored.
1115 */
1216export default class FormAutosubmitElement extends SprinklesElement {
1317 static tagName = "form-autosubmit" ;
1418 static refs = [ "button" ] ;
1519 static events = {
16- change : "submit " ,
17- input : "debouncedSubmit " ,
20+ change : "handleChange " ,
21+ input : "handleInput " ,
1822 } ;
1923
20- debouncedSubmit = debounce ( this . #submit. bind ( this ) , 250 ) ;
24+ beforeConnected ( ) {
25+ this . changeDebounce = this . hasAttribute ( "data-change-debounce" )
26+ ? parseInt ( this . getAttribute ( "data-change-debounce" ) )
27+ : 0 ;
28+ this . inputDebounce = this . hasAttribute ( "data-input-debounce" )
29+ ? parseInt ( this . getAttribute ( "data-input-debounce" ) )
30+ : 250 ;
2131
22- submit ( ) {
23- this . debouncedSubmit . trigger ( ) ;
32+ this . handleChange = debounce ( this . # submit. bind ( this ) , this . changeDebounce ) ;
33+ this . handleInput = debounce ( this . #submit . bind ( this ) , this . inputDebounce ) ;
2434 }
2535
2636 #submit( ) {
37+ // If one debounce triggers, we clear both
38+ // This avoids the two debounces being triggered close too each other
39+ this . handleChange . clear ( ) ;
40+ this . handleInput . clear ( ) ;
41+
42+ // Submit the form
2743 this . refs . button . click ( ) ;
2844 }
2945}
0 commit comments