I would like to know if I'm writing a plugin for jquery correctly. I followed the official guide and also added some tweaks that I've found from various sources over time.
While this works perfectly, I don't know if I'm doing something wrong.
This is the sample:
(function($)
{
var plugin = "my_plugin_name";
var methods = {
init : function(user_settings)
{
return this.each(function(index)
{
if(!$(this).hasClass("plugin_class"))
{
$(this).addClass("plugin_class");
var $this = $(this);
var data = $this.data(plugin);
if(!data)
{
var default_settings = {
optionA: "abc",
optionB: 123,
optionB: true
};
if(user_settings)
{
$.extend(true, default_settings, user_settings);
}
$this.data(plugin,
{
"settings": default_settings
});
}
privateMethod($this);
}
});
},
exposedMethodX : function(value) //$(selector).my_plugin_name("exposedMethodX", true)
{
console.log(value)
}
};
$.fn[plugin] = function(method)
{
if(methods[method])
{
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if(typeof method === "object" || !method)
{
return methods.init.apply(this, arguments);
}
else
{
alert("Method " + method + " does not exist");
}
};
function privateMethod(obj)
{
console.log(obj.data(plugin).settings);
}
})(jQuery);
$(selector).my_plugin_name()
will work, also$(selector).my_plugin_name("exposedMethodX", 123)
\$\endgroup\$