|
3 | 3 | // * use export to make it work with ES6 modules. |
4 | 4 | // * the addition of `const` to make it strict mode compatible. |
5 | 5 | // * ignore forms with "ignore-dirty" class, ignore hidden forms (closest('.tw-hidden')) |
| 6 | +// * extract the default options to make it available to other functions |
| 7 | +// * check if any form is dirty |
6 | 8 |
|
7 | 9 | /*! |
8 | 10 | * jQuery Plugin: Are-You-Sure (Dirty Form Detection) |
|
16 | 18 | * Version: 1.9.0 |
17 | 19 | * Date: 13th August 2014 |
18 | 20 | */ |
| 21 | +const defaultOptions = { |
| 22 | + 'message': 'You have unsaved changes!', |
| 23 | + 'dirtyClass': 'dirty', |
| 24 | + 'change': null, |
| 25 | + 'silent': false, |
| 26 | + 'addRemoveFieldsMarksDirty': false, |
| 27 | + 'fieldEvents': 'change keyup propertychange input', |
| 28 | + 'fieldSelector': ":input:not(input[type=submit]):not(input[type=button])" |
| 29 | +}; |
| 30 | + |
19 | 31 | export function initAreYouSure($) { |
20 | 32 |
|
21 | 33 | $.fn.areYouSure = function(options) { |
22 | 34 |
|
23 | | - var settings = $.extend( |
24 | | - { |
25 | | - 'message' : 'You have unsaved changes!', |
26 | | - 'dirtyClass' : 'dirty', |
27 | | - 'change' : null, |
28 | | - 'silent' : false, |
29 | | - 'addRemoveFieldsMarksDirty' : false, |
30 | | - 'fieldEvents' : 'change keyup propertychange input', |
31 | | - 'fieldSelector': ":input:not(input[type=submit]):not(input[type=button])" |
32 | | - }, options); |
| 35 | + var settings = $.extend({}, defaultOptions, options); |
33 | 36 |
|
34 | 37 | var getValue = function($field) { |
35 | 38 | if ($field.hasClass('ays-ignore') |
@@ -162,9 +165,7 @@ export function initAreYouSure($) { |
162 | 165 | if (!settings.silent && !window.aysUnloadSet) { |
163 | 166 | window.aysUnloadSet = true; |
164 | 167 | $(window).bind('beforeunload', function() { |
165 | | - const $forms = $("form:not(.ignore-dirty)").filter('.' + settings.dirtyClass); |
166 | | - const dirtyFormCount = Array.from($forms).reduce((res, form) => form.closest('.tw-hidden') ? res : res + 1, 0); |
167 | | - if (dirtyFormCount === 0) return; |
| 168 | + if (!triggersAreYouSure(settings)) return; |
168 | 169 |
|
169 | 170 | // Prevent multiple prompts - seen on Chrome and IE |
170 | 171 | if (navigator.userAgent.toLowerCase().match(/msie|chrome/)) { |
@@ -210,3 +211,8 @@ export function ignoreAreYouSure(selectorOrEl: string|Element|$) { |
210 | 211 | // because when using "enter" to submit a form, the "dirty" class will appear again before reloading. |
211 | 212 | $(selectorOrEl).addClass('ignore-dirty'); |
212 | 213 | } |
| 214 | + |
| 215 | +export function triggersAreYouSure(opts = {}) { |
| 216 | + const $forms = $('form:not(.ignore-dirty)').filter('.' + (opts.dirtyClass ?? defaultOptions.dirtyClass)); |
| 217 | + return Array.from($forms).some((form) => form.closest('.tw-hidden') === null); |
| 218 | +} |
0 commit comments