jQuery plugin structure
HTML
<p><a href="#" id="testItem">Test me</a><br>
<a href="#" id="changeItem">Make a change</a>
</p>
<p><a href="#" id="testItem2">Test me</a><br>
<a href="#" id="changeItem2">Make a change</a>
</p>
JavaScript
(function($) {
$.pluginName = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {}
}
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
$element.css("color","red");
if( plugin.settings.onFoo && typeof(plugin.settings.onFoo) === "function" ) {
plugin.settings.onFoo();
}
foo_private_method();
}
plugin.foo_public_method = function() {
$element.css({
color: "green",
textDecoration: "underline"
});
}
var foo_private_method = function() {
$element.text(plugin.settings.foo);
}
plugin.init();
}
$.fn.pluginName = function(options) {
return this.each(function() {
if (undefined == $(this).data('pluginName')) {
var plugin = new $.pluginName(this, options);
$(this).data('pluginName', plugin);
}
});
}
})(jQuery);
var testItem = $("#testItem").pluginName({
foo: "abc",
onFoo: function() {}
});
var testItem2 = $("#testItem2").pluginName();
$("#changeItem").click(function(e) {
e.preventDefault();
$("#testItem").data('pluginName').foo_public_method();
//$('#testItem').pluginName('foo_public_method'); // <-- doesn't work
});
$("#changeItem2").click(function(e) {
e.preventDefault();
$("#testItem2").data('pluginName').foo_public_method();
});