Last active
August 29, 2015 14:00
-
-
Save gosukiwi/11274187 to your computer and use it in GitHub Desktop.
jQuery plugin boilerplate
This file contains 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
/* | |
* Minimal tooltip for jQuery by Federico Ramirez | |
* | |
* Usage: $('#myElement').myPlugin({}); | |
* $('#myElement').myPlygin('myMethod', arg1, arg2); | |
* */ | |
;(function ($, window, document, undefined) { | |
'use strict'; | |
var pluginName = 'myPlugin', | |
defaults = { | |
myParam: 'myValue' | |
}; | |
// The actual plugin constructor | |
function Plugin (element, options) { | |
this.$el = $(element); | |
this.settings = $.extend({}, defaults, options); | |
this._defaults = defaults; | |
this._name = pluginName; | |
this.init(); | |
} | |
Plugin.prototype = { | |
init: function () { | |
// initialize your plugin | |
// return the element for chainability | |
return this.$el; | |
}, | |
someMethod: function () { | |
// do something in the method | |
// return the element for chainability, if your method | |
// returns some value just remove this | |
return this.$el; | |
} | |
}; | |
// Instantiation or method call, accordingly | |
$.fn[pluginName] = function (options) { | |
var args = Array.prototype.slice.call(arguments); | |
this.each(function() { | |
var instance = $.data(this, 'plugin_' + pluginName), | |
method; | |
if (!instance) { | |
$.data( this, 'plugin_' + pluginName, new Plugin(this, options)); | |
} else { | |
method = args.shift(); | |
return instance[method].apply(instance, args); | |
} | |
}); | |
// chain jQuery functions | |
return this; | |
}; | |
})(jQuery, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment