From c6ca6afa6691ce55cd3c8c9deb11c500fc5f441a Mon Sep 17 00:00:00 2001 From: Andrew Kozlov Date: Thu, 29 Oct 2015 15:03:12 +0500 Subject: [PATCH] Add delay option By default there is still no delay, but now you able to define it. --- jquery.formwatch.js | 52 +++++++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/jquery.formwatch.js b/jquery.formwatch.js index 7b591bb..213fb8b 100644 --- a/jquery.formwatch.js +++ b/jquery.formwatch.js @@ -1,10 +1,12 @@ /* jQuery FormWatch: easily monitor changes in form data. https://github.com/kylefox/jQuery-FormWatch - Version 0.1 + Version 0.2 */ (function($) { - + var timeoutId; + var delay = 0; + function _eventArgs() { return $.map(arguments, function(arg) { if('deparam' in $) { @@ -13,53 +15,71 @@ return arg; }); } - + + function _checkChangeWithTimeout() { + if (typeof timeoutId != 'undefined') { + clearTimeout(timeoutId) + } + + var that = this + timeoutId = setTimeout(function() { + _checkChange.apply(that) + }, delay) + } + 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.bind('change', _checkChange); - form.bind('keydown', _checkChange); - form.bind('keyup', _checkChange); + 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.unbind('change', _checkChange); - form.unbind('keydown', _checkChange); - form.unbind('keyup', _checkChange); + 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() { + + $.fn.watch = function(_delay) { + if (_delay) { + delay = _delay + } + $(this).each(function(idx, elm) { _watch($(elm)); }); }; - + $.fn.unwatch = function() { $(this).each(function(idx, elm) { _unwatch($(elm)); }); }; - -})(jQuery); \ No newline at end of file + +})(jQuery);