-
Notifications
You must be signed in to change notification settings - Fork 7
/
jquery.formwatch.js
65 lines (58 loc) · 1.57 KB
/
jquery.formwatch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
jQuery FormWatch: easily monitor changes in form data.
https://github.com/kylefox/jQuery-FormWatch
Version 0.1
*/
(function($) {
function _eventArgs() {
return $.map(arguments, function(arg) {
if('deparam' in $) {
return $.deparam(arg);
}
return arg;
});
}
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.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.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);