Created
August 20, 2015 07:34
-
-
Save SCIF/500a1047fbb5cc29e83d to your computer and use it in GitHub Desktop.
jquery.draftsaver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* fields: array of names of tracked fields. All inputs and textareas by default (selector: ':input') | |
* always_update: array of names of fields, which will be added to request always. For example: '_token' | |
* | |
* @author Zhuravlev Alexander, [email protected] | |
* @licence MIT, http://opensource.org/licenses/mit-license.php | |
*/ | |
(function ($) { | |
$.fn.draftsaver = function (options) { | |
var settings = $.extend({ | |
'url': undefined, | |
'ajaxSettings': {}, | |
'fields': [], | |
"ignoreSelector": ':button,:submit,:reset,:file', | |
"updateInterval": 3000, | |
"alwaysUpdate": [], | |
"updateOnlyChanged": true | |
}, options); | |
settings.ajaxSettings = $.extend({ | |
'dataType': 'json', | |
'type': 'POST' | |
}, options.ajaxSettings); | |
var form = this; | |
settings.ajaxSettings.url = settings.url || form.attr('action'); | |
var input_selector = ':input'; | |
if (settings.fields.length > 0) { | |
input_selector = ''; | |
settings.fields.forEach(function (val) { | |
input_selector += '[name="' + val + '"],'; | |
}); | |
settings.alwaysUpdate.forEach(function (val) { | |
input_selector += '[name="' + val + '"],'; | |
}); | |
input_selector = input_selector.substr(0, input_selector.length - 1); | |
} | |
var fields = form.find(input_selector).not(settings.ignoreSelector); | |
function is_changed(field) { | |
return (field.data('old-draft-text') != field.val()); | |
} | |
function save_draft(data) { | |
data = data || {}; | |
var temp = settings.ajaxSettings; | |
if ( ! settings.updateOnlyChanged) { | |
data = {}; | |
form.find(':input:not(:button)').each(function() { | |
data[$(this).attr('name')] = $(this).val(); | |
}); | |
} | |
temp.data = data; | |
jQuery.ajax(temp); | |
} | |
var action = function () { | |
var changed = false; | |
var changed_data = {}; | |
fields.each(function () { | |
var field = $(this); | |
if (is_changed(field)) { | |
changed = true; | |
changed_data[field.attr('name')] = field.val() | |
field.data('old-draft-text', field.val()); | |
} | |
}); | |
if (changed) { | |
save_draft(changed_data); | |
} | |
}; | |
// fills buffers by initial data | |
fields.each(function () { | |
$(this).data('old-draft-text', $(this).val()); | |
}); | |
setInterval(action, settings.updateInterval); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment