Skip to content

Instantly share code, notes, and snippets.

@meeDamian
Created April 25, 2012 19:03
Show Gist options
  • Save meeDamian/2492332 to your computer and use it in GitHub Desktop.
Save meeDamian/2492332 to your computer and use it in GitHub Desktop.
[ JS | template ] Base structure of jQuery plugin (with methods and options
(function($) {
/**
* IMPORTANTE!
* if you call methods via methods._methodName(); entire context is LOST,
* therefore you cannot reference to your object as `this`, so a good way
* to fix it is to call them like that:
* methods._private.call($(this)); // which will keep object as `this`
**/
// this object is available only inside of this function
var methods = {
init:function(options){
console.log("plugin initialized");
// extends settings if init called with map passed
if(typeof options =="object") settings = $.extend(settings,options);
return this.each(function(){
// contents of main action
methods.public.call($(this));
});
},
public:function( this ) {
console.log("public() method called");
// may be called from outside of plugin body,
// ex. $(body).pluginName('public');
// or, when called internally may be called as:
// methods.private.call($(this));
},
_private:function( this ) {
console.log("_private() method called");
// may not be called from outside of the plugin body
// only way to call it is: methods._private.call($(this));
}
}
// default plugin settings; overriten when plugin called with map passed
var settings = {
param1: null,
param2: null
}
/* handles:
* calls without parameters: $(body).pluginName(); - runs methods.init();
* calls with particular function: $(body).pluginName('public'); - runs methods.public();
* calls with params map passed $(body).pluginName({param1:"black",param2:"Fuck You, that's why!"}); - calls methods.init(map);
* and extends settings object by parameters passed via map
* invalid calls: returns textual errors
*/
$.fn.pluginName = function( method ) {
// second condition here will disable calling functions starting from "_".
// ex. `$(selector).filterGroup('_someFunction');` will return error
if( methods[method] && method[0]!=="_" ) return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
else if ( typeof method === 'object' || ! method ) return methods.init.apply( this, arguments );
else $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment