I am want to build a plugin with accessible methods and options, this for a complex plugin. I need the methods to be accessible outside the plugin because if somebody ads someth
An alternative:
var Plugin = function($self, options) {
this.$self = $self;
this.options = $.extend({}, $.fn.plugin.defaults, options);
};
Plugin.prototype.display = function(){
console.debug("Plugin.display");
};
Plugin.prototype.update = function() {
console.debug("Plugin.update");
};
$.fn.plugin = function(option) {
var options = typeof option == "object" && option;
return this.each(function() {
var $this = $(this);
var $plugin = $this.data("plugin");
if(!$plugin) {
$plugin = new Plugin($this, options);
$this.data("plugin", $plugin);
}
if (typeof option == 'string') {
$plugin[option]();
} else {
$plugin.display();
}
});
};
$.fn.plugin.defaults = {
propname: "propdefault"
};
Usage:
$("span").plugin({
propname: "propvalue"
});
$("span").plugin("update");
This absurdly resembles the Twitter Bootstrap's JavaScript template. But, it wasn't completely taking from there. I have a long history of using .data().
Don't forget to wrap it appropriately.