Parcourir la source

Improve form changes detection

Original form data is compared to current data when exiting the page. The confirm dialog show up only if the data has been changed.
Emmanuel Vella il y a 11 ans
Parent
commit
cddc7a79e3
2 fichiers modifiés avec 29 ajouts et 24 suppressions
  1. 1 1
      Resources/public/base.js
  2. 28 23
      Resources/public/jquery/jquery.confirmExit.js

+ 1 - 1
Resources/public/base.js

@@ -1,7 +1,7 @@
 jQuery(document).ready(function() {
     jQuery('html').removeClass('no-js');
     if (window.SONATA_CONFIG.CONFIRM_EXIT) {
-        jQuery('.sonata-ba-form form').confirmExit(window.SONATA_TRANSLATIONS.CONFIRM_EXIT);
+        jQuery('.sonata-ba-form form').confirmExit();
     }
     Admin.add_pretty_errors(document);
     Admin.add_filters(document);

+ 28 - 23
Resources/public/jquery/jquery.confirmExit.js

@@ -7,32 +7,37 @@
 * http://www.opensource.org/licenses/mit-license.php
 */
 (function ($) {
-	$.fn.confirmExit = function(message) {
-		var confirmExit = false;
+    $.fn.confirmExit = function() {
+        $(this).attr('data-original', $(this).serialize());
 
-		$('input, textarea, select', this).on('change keyup', function() {
-			// Do not set the event handler if not needed
-			if (!confirmExit) {
-				confirmExit = true;
+		$(this).on('submit', function() {
+            $(this).removeAttr('data-original');
+        });
 
-				window.onbeforeunload = function(event) {
-					var e = event || window.event;
+        return $(this);
+	}
 
-					// For old IE and Firefox
-					if (e) {
-						e.returnValue = message;
-					}
+    $(window).on('beforeunload', function(event) {
+        var e = event || window.event,
+            message = window.SONATA_TRANSLATIONS.CONFIRM_EXIT,
+            changes = false
+        ;
 
-					return message;
-				}
-			}
-		});
+        $('form[data-original]').each(function() {
+            if ($(this).attr('data-original') !== $(this).serialize()) {
+                changes = true;
 
-		this.submit(function() {
-			window.onbeforeunload = null;
-			confirmExit = false;
-		});
+                return;
+            }
+        });
 
-		return this;
-	}
-	})(jQuery);
+        if (changes) {
+            // For old IE and Firefox
+            if (e) {
+                e.returnValue = message;
+            }
+
+            return message;
+        }
+    });
+})(jQuery);