Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created October 25, 2010 13:13
Show Gist options
  • Save badsyntax/644924 to your computer and use it in GitHub Desktop.
Save badsyntax/644924 to your computer and use it in GitHub Desktop.
// In the quest to find a good jQuery plugin design pattern,
// I have collated some of the techniques I have used in the past in this file.
(function($, window, document, undefined){
$.fn.myplugin = function(method){
var pluginName = 'myplugin', args = arguments, val = undefined;
this.each(function(){
// get plugin object reference from base element
var obj = $.data( this, pluginName );
// if the plugin object and method exists then execute it
if ( obj && typeof method === 'string' && obj[method]) {
// execute a public method, store the return value
val = obj[method].apply( obj, Array.prototype.slice.call( args, 1 ) );
}
// plugin does not exist
else if ( !obj && ( typeof method === 'object' || ! method ) ) {
// initiate the plugin
$.data( this, pluginName, new myplugin(this, method, pluginName) );
}
});
// return the value from a method, or the jQuery object
return val || this;
};
// constructor: define private members
function myplugin(element, options, pluginName ){
// set private constructor data
var self = this, privateVar1, privateVar2;
// set public object data
this.element = $( element );
this.pluginName = pluginName;
this.options = $.extend({
// default options here
}, options);
// private methods, only available to the constructor
function privateFunc1(){
alert('Private func 1');
}
function privateFunc2(){
alert('Private func 2');
}
// privleged methods (public, but have access to private members)
this.privileged1 = function(){
privateFunc1.call();
};
this.privileged2 = function(){
privateFunc2.call();
};
// nested objects
this.nestedObject = {
func1: {
// it's impossible to access parent's parent without using a reference
// access 'self'
},
func1: {
// access 'self'
}
};
};
// public members
// this can be used to provide a public API to the plugin object
myplugin.prototype = {
publicVar1 : true,
publicVar2 : false,
plugin : function(){
return this;
},
publicFunc1: function(){
// i can only access public or privileged members
},
publicFunc2: function(){
// i can only access public or privileged members
}
};
var plugin =
$('#demo')
// initiate the plugin
.myplugin()
// return the plugin instance
.myplugin('plugin');
// execute a priveleged or public method
// access to public or priveleged members is allowed
// eg:
// plugin.privileged1();
})(this.jQuery, this, this.document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment