Skip to content

Add delay option #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 36 additions & 16 deletions jquery.formwatch.js
Original file line number Diff line number Diff line change
@@ -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 $) {
Expand All @@ -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);

})(jQuery);