Skip to content

Instantly share code, notes, and snippets.

@ehynds
Forked from StevenBlack/jquery.pluginOutline.js
Created April 8, 2010 14:46
Show Gist options
  • Save ehynds/360140 to your computer and use it in GitHub Desktop.
Save ehynds/360140 to your computer and use it in GitHub Desktop.
// Skeleton jQuery Plugin (OO)
(function($){
$.fn.myPlugin = function( options ){
options = $.extend( {}, $.fn.myPlugin.defaults, options );
return this.each(function(){
// create a new object & store it in the element's data for easy access
$(this).data('myPlugin', new MyPlugin(this, options));
});
}
var MyPlugin = function(element, options){
// add the element as a property
this.element = element;
return this;
}
// public prototype methods
MyPlugin.prototype.method = function(){
return;
}
// private function
function func(){
return;
}
// Plugin Defaults
$.fn.myPlugin.defaults = {
prop: 'some value'
}
})(jQuery);
// usage
$(function(){
// use plugin
$("div").myPlugin();
// get the object
var obj = $("div").data("myPlugin");
// call a method on the object
obj.method();
});
// Skeleton jQuery Plugin (traditional)
(function($){
$.fn.myPlugin = function( options ){
// options.
options = $.extend( {}, $.fn.myPlugin.defaults, options );
// Go through the matched elements and return the jQuery object.
return this.each(function(){
var $this = $(this);
});
};
// Public defaults.
$.fn.myPlugin.defaults = {
prop: 'some value'
};
// Private functions.
function func(){
return;
};
// Public functions.
$.fn.myPlugin.func = function(){
return;
};
})(jQuery);
// usage
$(function(){
// use plugin
$("div").myPlugin();
});
@StevenBlack
Copy link

For a variety of reasons I'm leaning towards separating options and settings, leaving options in an as-provided state, and working off settings.

Therefore line-5 becomes

settings = $.extend( {}, $.fn.myPlugin.defaults, options );

... and settings becomes the object of discourse for configuration.

Another leaning: Depending on nature of the plugin, making the plugin's settings a full-bird member so it is externally visible and editable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment