Skip to content

Instantly share code, notes, and snippets.

@daftspunk
Last active March 20, 2016 21:23
Show Gist options
  • Save daftspunk/8001216 to your computer and use it in GitHub Desktop.
Save daftspunk/8001216 to your computer and use it in GitHub Desktop.
JS Plugin Boilerplate
/*
* Example plugin
*
* Data attributes:
* - data-control="example" - enables the plugin on an element
* - data-option="value" - an option with a value
*
* JavaScript API:
* $('a#someElement').myPlugin({ option: 'value' })
*
* Dependences:
* - Some other plugin (filename.js)
*/
+function ($) { "use strict";
// EXAMPLE CLASS DEFINITION
// ============================
var Example = function(element, options) {
this.options = options
this.$el = $(element)
// Init
this.init()
}
Example.DEFAULTS = {
option: 'default'
}
Example.prototype.init = function() {
// Public properties
this.something = false
// Init with no arguments
}
Example.prototype.someFunction = function() {
// Do stuff
}
// EXAMPLE PLUGIN DEFINITION
// ============================
var old = $.fn.myPlugin
$.fn.myPlugin = function (option) {
var args = Array.prototype.slice.call(arguments, 1), result
this.each(function () {
var $this = $(this)
var data = $this.data('oc.example')
var options = $.extend({}, Example.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('oc.example', (data = new Example(this, options)))
if (typeof option == 'string') result = data[option].apply(data, args)
if (typeof result != 'undefined') return false
})
return result ? result : this
}
$.fn.myPlugin.Constructor = Example
// EXAMPLE NO CONFLICT
// =================
$.fn.myPlugin.noConflict = function () {
$.fn.myPlugin = old
return this
}
// EXAMPLE DATA-API
// ===============
$(document).on('click.oc.myplugin', '[data-control="example"]', function() {
$(this).myPlugin()
});
}(window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment