Skip to content

Instantly share code, notes, and snippets.

@tanraya
Created October 29, 2015 09:41
Show Gist options
  • Save tanraya/48c232558ea1e8a1421b to your computer and use it in GitHub Desktop.
Save tanraya/48c232558ea1e8a1421b to your computer and use it in GitHub Desktop.
/*
jQuery FormWatch: easily monitor changes in form data.
https://github.com/kylefox/jQuery-FormWatch
Version 0.1
*/
(function($) {
var timeout_id;
function _eventArgs() {
return $.map(arguments, function(arg) {
if('deparam' in $) {
return $.deparam(arg);
}
return arg;
});
}
function _checkChangeWithTimeout() {
if (typeof timeout_id != 'undefined') {
clearTimeout(timeout_id)
}
var that = this
timeout_id = setTimeout(function() {
_checkChange.apply(that)
}, 400)
}
function _checkChange() {
var form = $(this),
oldData = form.data('oldData'),
originalData = form.data('originalData'),
newData = form.serialize(),
args = _eventArgs(newData, oldData, originalData);
if(newData !== oldData) {
form.trigger('modified', args);
form.data('dirty', true);
}
if(form.data('dirty') && newData === originalData) {
form.trigger('reverted', args);
form.data('dirty', false);
}
form.data('oldData', newData);
};
function _watch(form) {
var formData = form.serialize();
form.on('change', _checkChangeWithTimeout);
form.on('keydown', _checkChangeWithTimeout);
form.on('keyup', _checkChangeWithTimeout);
form.data('dirty', false);
form.data('oldData', formData);
form.data('originalData', formData);
};
function _unwatch(form) {
form.off('change', _checkChangeWithTimeout);
form.off('keydown', _checkChangeWithTimeout);
form.off('keyup', _checkChangeWithTimeout);
form.data('dirty', null);
form.data('oldData', null);
form.data('originalData', null);
}
$.fn.watch = function() {
$(this).each(function(idx, elm) {
_watch($(elm));
});
};
$.fn.unwatch = function() {
$(this).each(function(idx, elm) {
_unwatch($(elm));
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment