jQuery Plugin Pattern #2
HTML
<div id="foo"></div>
<div id="bar"></div>
JavaScript
/**
* jQuery plugin pattern by Marcus Ekwall <mekwall(at)writeless.se>
**/
/*
yo dawg, the things i didn't like:
- overcomplicating the constructor. no need to extend it onto $.fn.myPlugin, and no need to extend the prototype since you're not merging anything.
- on the same note, "new MyPlugin(this, options)" is a lot cleaner than "new $.fn.MyPlugin.instance(this, options)._init(arguments)" - MyPlugin itself can be the constructor (ditch instance), and call _init within the constructor. and why pass arguments init _init?
- $.data is faster than $.fn.data because it doesn't throw events
- options weren't exposed outside the plugin so you couldn't set defaults once, across the board, for all future instances
- there's no protection against calling internal methods with this API
*/
(function($){
// plugin handler
$.fn.myPlugin = function(options){
// override defaults with passed options
options = $.extend({}, $.fn.myPlugin.defaults, options);
// iterate passed elements
return this.each(function(){
if (!$.data(this, "myPlugin-instance")) {
$.data(this, "myPlugin-instance", new MyPlugin(this, options));
}
}).data("myPlugin-instance");
}
// expose so the defaults can be overwritten before
// any instances are created outside this plugin
$.fn.myPlugin.defaults = {
someText: "foo!",
ajaxText: "Hello world!"
};
// instance constructor
function MyPlugin(element, options){
this.element = $(element);
this.options = options;
this._init();
}
// prototype
MyPlugin.prototype = {
// return to element
end: function(){
return this.element;
},
// set/return an option
option: function(option, value){
if (value) {
this.options[option] = value;
}...