Skip to content

Instantly share code, notes, and snippets.

@markembling
Created September 30, 2022 09:00
Show Gist options
  • Save markembling/ad4c217c05264cfa796bb4fb4f826292 to your computer and use it in GitHub Desktop.
Save markembling/ad4c217c05264cfa796bb4fb4f826292 to your computer and use it in GitHub Desktop.
/*
* Change detection for forms
*
* @author Mark Embling
*
* Initialise on applicable forms using the jQuery plugin.
* Recommended one per page but this is not a requirement.
*
* Copyright © 2022 Mark Embling
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
; (function ($) {
var ChangeAwareForm = function (element, options) {
this.options = null;
this.$formElement = null;
this.unsavedChanges = 0;
this.init(element, options);
};
ChangeAwareForm.DEFAULTS = {
log: false // Whether to announce changes via console.log
}
ChangeAwareForm.prototype.init = function (element, options) {
this.$formElement = $(element);
this.options = $.extend({}, ChangeAwareForm.DEFAULTS, options);
this.initChangeHandlers();
this.initSubmitHandler();
this.initWindowHandler();
};
ChangeAwareForm.prototype.initChangeHandlers = function () {
var self = this;
self.$formElement.find('input:not(.no-change-detect,.typeahead)').change(function (ev) {
self.registerChange(ev);
});
self.$formElement.find('textarea:not(.no-change-detect)').change(function (ev) {
self.registerChange(ev);
});
self.$formElement.find('select:not(.no-change-detect)').change(function (ev) {
self.registerChange(ev);
});
self.$formElement.find("input[type='checkbox']:not(.no-change-detect)").on('switchChange.bootstrapSwitch', function (ev) {
self.registerChange(ev);
});
self.$formElement.find('.date:not(.no-change-detect)').on('dp.change', function (ev) {
self.registerChange(ev);
});
};
ChangeAwareForm.prototype.initSubmitHandler = function () {
var self = this;
self.$formElement.submit(function () {
self.unsavedChanges = 0;
});
};
ChangeAwareForm.prototype.initWindowHandler = function () {
var self = this;
window.addEventListener("beforeunload", function (e) {
if (self.unsavedChanges > 0) {
// Prevents the page from being unloaded (the browser should display a prompt.)
// See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
e.preventDefault();
e.returnValue = "";
}
});
};
ChangeAwareForm.prototype.registerChange = function (ev) {
this.unsavedChanges += 1;
if (this.options.log) {
console.log("ChangeAwareForm change registered", ev)
}
};
ChangeAwareForm.prototype.hasChanges = function () {
return this.unsavedChanges > 0;
};
ChangeAwareForm.prototype.resetChanges = function () {
this.unsavedChanges = 0;
};
//
// jQuery plugin
//
$.fn.changeAware = function (option) {
function initOrGetChangeAwarenessForFormElement(formElement) {
var $formElement = $(formElement);
var changeAwareForm = $formElement.data("SFCF_ChangeAwareForm");
if (!changeAwareForm) {
var options = (typeof option == 'object' && option);
changeAwareForm = new ChangeAwareForm($formElement, options);
$formElement.data("ChangeAwareForm", changeAwareForm);
}
return changeAwareForm;
}
// If the first argument is a string, then this is a function call.
// Ensure the ChangeAwareForm is initialised and then call the function (if available),
// returning the result.
if (typeof option == "string") {
var funcName = option;
var funcArgs = Array.prototype.slice.call(arguments, 1);
var returnValue;
this.each(function () {
var cr = initOrGetChangeAwarenessForFormElement(this);
if (typeof cr[funcName] === "function") {
returnValue = cr[funcName](funcArgs);
} else {
throw new Error("No function named " + funcName + " exists.");
}
});
return returnValue !== undefined ? returnValue : this;
}
// If this is not a function call, just initialise the character counter and return the
// result of this.each, in typical jQuery plugin fashion.
return this.each(function () {
initOrGetChangeAwarenessForFormElement(this);
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment