Skip to content

Instantly share code, notes, and snippets.

@sveetch
Created May 23, 2017 15:49
Show Gist options
  • Save sveetch/aafb4962faaabd1d3613474c8a5de2fe to your computer and use it in GitHub Desktop.
Save sveetch/aafb4962faaabd1d3613474c8a5de2fe to your computer and use it in GitHub Desktop.
jQuery plugin basic sample
/*
* jQuery plugin basic sample
*
* Usage exemple:
*
* $('.something').sampleplugin();
* $('.something').sampleplugin('destroy');
*
*/
(function ( $ ) {
/*
* Plugin extensions calling logic
*/
$.fn.sampleplugin = function(method) {
// Specific public method called
if ( extensions[method] ) {
return extensions[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
// Default public method to init the plugin
} else if ( typeof method === 'object' || ! method ) {
return extensions.init.apply( this, arguments );
// Unknow called method
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.sampleplugin' );
}
};
// Default public plugin settings
var default_settings = {};
/*
* Plugin event methods
*/
var events = {
/*
* Sample event
*/
myevent: function(event) {
event.preventDefault();
var $container = $(this);
}
};
/*
* Plugin extension methods
*/
var extensions = {
/*
* Initialize plugin, default public method, must be called first
*/
init : function(options) {
var settings = $.extend(default_settings, options);
return this.each(function() {
var $container = $(this);
// Bind sample event
$container.on("click.sampleplugin.myevent", events.myevent);
});
},
/*
* Destroy instance from container and all its attached stuff
*/
destroy : function() {
return this.each(function() {
var $container = $(this);
// 3. Disable every event from container
$container.off(".sampleplugin");
});
}
};
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment