1
1
$ ( function ( ) {
2
+ // The main function that serializes the form and sends it to the save draft endpoint.
3
+ //
4
+ // It is wrapped in _.throttle so it is called on the trailing edge at most
5
+ // once in a 3 second window. More casually this means no matter how many
6
+ // times the function is called within a 3 second window, the code will only
7
+ // actually be executed once at the end of the window.
8
+ //
9
+ // The draft is therefore saved periodically and after things have "settled,"
10
+ // but not so often as to flood the server with requests.
2
11
var currentDraftRequest ;
3
- const saveDraftDebounced = _ . debounce ( function ( e ) {
12
+ const saveDraftThrottled = _ . throttle ( function ( e ) {
4
13
let $target = $ ( e . target ) ;
5
14
let $form = $target . closest ( "form" ) ;
6
15
let draftsURL = $form . data ( "drafts-url" ) ;
@@ -36,21 +45,17 @@ $(function() {
36
45
37
46
$form . trigger ( "draft:error" , [ jqXHR , textStatus , errorThrown ] ) ;
38
47
39
- // Retry. Rely on debounce to coalesce multiple calls into one retry.
40
- saveDraftDebounced ( e ) ;
48
+ // Retry. Rely on throttle to coalesce multiple calls into one retry.
49
+ saveDraftThrottled ( e ) ;
41
50
} ,
42
51
} ) ;
43
- } , 2500 ) ;
52
+ } , 3000 , { leading : false } ) ;
44
53
54
+ // Save drafts for forms where data-drafts-url is present as an attribute.
45
55
const $formsWithDraftsURLs = $ ( "form[data-drafts-url]" ) ;
46
- $formsWithDraftsURLs . on ( "blur change" , ":input" , saveDraftDebounced )
47
-
48
- // After the draft is discarded, reload the page to empty out all fields and
49
- // start from scratch cleanly.
50
- $ ( "a.discard-draft-link" ) . on ( "ajax:complete" , function ( e ) {
51
- location . reload ( true ) ;
52
- } ) ;
56
+ $formsWithDraftsURLs . on ( "blur change" , ":input" , saveDraftThrottled )
53
57
58
+ // Trigger validation and cursor restoration for draft-enabled forms
54
59
$formsWithDraftsURLs . each ( function ( ) {
55
60
const $form = $ ( this ) ;
56
61
if ( $form . data ( "draft-restored" ) ) {
@@ -60,4 +65,10 @@ $(function() {
60
65
$ ( "#" + $form . data ( "draft-focused-dom-id" ) ) . focus ( ) ;
61
66
}
62
67
} ) ;
68
+
69
+ // After the draft is discarded, reload the page to empty out all fields and
70
+ // start from scratch cleanly.
71
+ $ ( "a.discard-draft-link" ) . on ( "ajax:complete" , function ( e ) {
72
+ location . reload ( true ) ;
73
+ } ) ;
63
74
} ) ;
0 commit comments