/** * Script for blocking repeated form submits * * @example * * // automatic mode * $('form').formSubmitLock(); * * // manual mode * if ($('form').formSubmitLock('getLocked')) return; * $('form').formSubmitLock('lock'); * $('form').formSubmitLock('unlock'); * * * @version 1.0.0 * @requires jQuery */ (function ($) { 'use strict'; var debug = false; /** * @constructor */ var FormSubmitLock = function () { this.construct.apply(this, arguments); }; FormSubmitLock.prototype.construct = function ($form, options) { debug && console.log('FormSubmitLock.construct'); this.$form = $form; this.options = options; }; FormSubmitLock.prototype.bindEvents = function () { debug && console.log('FormSubmitLock.bindEvents'); this.$form.on('submit.' + this.options.nameProp, $.proxy(this.onSubmit, this)); }; FormSubmitLock.prototype.unbindEvents = function () { debug && console.log('FormSubmitLock.unbindEvents'); this.$form.off('submit.' + this.options.nameProp); }; FormSubmitLock.prototype.onSubmit = function (e) { if (this.getLocked()) { debug && console.log('FormSubmitLock.onSubmit preventDefault'); e.preventDefault(); e.stopPropagation(); } else { this.lock(); } }; FormSubmitLock.prototype.lock = function () { debug && console.log('FormSubmitLock.lock'); this.$form.data(this.options.lockProp, true); }; FormSubmitLock.prototype.unlock = function () { debug && console.log('FormSubmitLock.unlock'); this.$form.data(this.options.lockProp, false); }; FormSubmitLock.prototype.getLocked = function () { debug && console.log('FormSubmitLock.getLocked'); return !!this.$form.data(this.options.lockProp); }; /** * @param {Object|String|?} option Method * @return {$.fn} */ $.fn.formSubmitLock = function submitLock(option) { if (!this.is('form')) { throw new Error('FormSubmitLock: Target element is not a "form"'); } var $this = this.first(), options = $.extend({}, $.fn.formSubmitLock.defaults, typeof option == 'object' && option), instance = $this.data(options.nameProp); if (null == instance) { instance = new FormSubmitLock($this, options); $this.data(options.nameProp, instance); if (null == option) instance.bindEvents(); } if (instance && typeof option === 'string') { return instance[option](); } return this; }; $.fn.formSubmitLock.defaults = { nameProp: 'formSubmitLock', lockProp: 'formSubmitLock.locked' }; })(window.jQuery);