I am currently developing a rather complex jQuery plugin. One that I am designing to be extensible. The quandary I have is how to exactly provide my users with the APIs available to them.
There are two methods that I can come up with:
-
Provide the API via an object in the global scope
This is the method I am currently using. I do it similar to this:
(function ($, win, undefined) { //main plugin functionality function pluginStuff() { /*...including method calling logic...*/ } //register function with jQuery $.fn.extend({ Plugin: pluginStuff }); //register global API variable win.PluginAPI = { extendMe: {}, getVar: function() {} }; })(jQuery, window);Unfortunately since I impliment the standard
$().plugin('method')architecture its a little strange to have to use the jQuery method for some things and the API variable for others. -
Provide the API via an object placed in jQuery
I toyed with this method as well but its best practice to take up only a single slot in jQueries
fnscope, as not to crowd the jQuery variable. In this method I would put my api variable in$.fninstead of thewindow://register function with jQuery $.fn.extend({ Plugin: pluginStuff }); //register global API variable $.fn.PluginAPI = { extendMe: {}, getVar: function() {} };I would rather not break this convention and take up two places.
Now that I write this I can see a third option where I assign my plugins slot in jQuery’s fn scope to be an object:
$.fn.Plugin = { plugin: pluginStuff, api: { extendMe: {}, getVar: function() {} } };
but how well received would this be if users had to do $('#elm').Plugin.plugin({ setting: 'value' }) to create a new instance of the plugin?
Any help or pointers would be greatly appreciated.
Please Note: I’m am not looking for a way to incorporate the API object into my plugin functionality. I am looking for a way to keep it separately modularized, but intuitively available for use/extension.
The method I eventually decided to use was registering the plugin under the
fnnamespace and the api variable under the jQuery$namespace. Since methods and options set operate on an instance of the plugin$.fnis the best choice.However, the API is global and does not link to a single instance. In this case
$.fndoesn’t quite fit. What I ended up using was something similar to this:now you can create an use a plugin object as expected:
and you can easily extend and access the API:
Thanks for the help everyone!