Last active
March 1, 2017 01:22
-
-
Save jacerider/bf60fefd90bb617d48f9ced283601efd to your computer and use it in GitHub Desktop.
A jQuery Plugin Boilerplate
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
(function ($, Drupal, window, document) { | |
'use strict'; | |
var pluginName = 'uxFormInput'; | |
function Plugin(element, options) { | |
this.element = element; | |
this._name = pluginName; | |
this._defaults = $.fn.uxFormInput.defaults; | |
this.options = $.extend({}, this._defaults, options); | |
this.init(); | |
} | |
// Avoid Plugin.prototype conflicts | |
$.extend(Plugin.prototype, { | |
// Initialization logic | |
init: function () { | |
this.buildCache(); | |
this.bindEvents(); | |
}, | |
// Remove plugin instance completely | |
destroy: function () { | |
this.unbindEvents(); | |
this.$element.removeData(); | |
}, | |
// Cache DOM nodes for performance | |
buildCache: function () { | |
this.$element = $(this.element); | |
}, | |
// Bind events that trigger methods | |
bindEvents: function () { | |
var _this = this; | |
_this.$element.on('click' + '.' + _this._name, function () { | |
_this.someOtherFunction.call(_this); | |
}); | |
}, | |
// Unbind events that trigger methods | |
unbindEvents: function () { | |
this.$element.off('.' + this._name); | |
}, | |
someOtherFunction: function () { | |
alert('I promise to do something cool!'); | |
this.callback(); | |
}, | |
callback: function () { | |
var onComplete = this.options.onComplete; | |
if (typeof onComplete === 'function') { | |
onComplete.call(this.element); | |
} | |
} | |
}); | |
$.fn.uxFormInput = function (options) { | |
this.each(function () { | |
if (!$.data(this, pluginName)) { | |
$.data(this, pluginName, new Plugin(this, options)); | |
} | |
}); | |
return this; | |
}; | |
$.fn.uxFormInput.defaults = {}; | |
Drupal.behaviors.uxForm = { | |
attach: function (context) { | |
var $context = $(context); | |
$context.find('.ux-form-input').once('ux-form-input').uxFormInput(); | |
}, | |
detach: function (context) { | |
var $context = $(context); | |
$context.find('.ux-form-input').data('uxFormInput').destroy(); | |
} | |
}; | |
})(jQuery, Drupal, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment