Created
May 23, 2017 15:49
-
-
Save sveetch/aafb4962faaabd1d3613474c8a5de2fe to your computer and use it in GitHub Desktop.
jQuery plugin basic sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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