jQuery plugin with its own API
I am writing my first jQuery plugin and I want to be able to do this:
var myPluginVar = $("someElement").myPlugin();
myPluginVar.customFunctionCallWithinPlugin();
Any idea how to go about it?
EDIT
Please visit http://flowplayer.o开发者_JAVA百科rg/tools/using.html#api to see what i mean
You could achieve this design with something similar to the following. I have wrapped the plugin definition within an anonymous function to keep PluginObj
from polluting the global namespace.
(function($) {
function PluginObj() {
// construct stuff
}
PluginObj.prototype.customFunctionCallWithinPlugin = function() {
// do stuff
};
$.fn.myPlugin = function() {
return new PluginObj();
};
})(jQuery);
The jQuery method returns a new object with the methods you define. This is a non-standard design for a jQuery plugin though, so if you plan to distribute it make sure it is thoroughly documented.
You may have to return an instance of the plugin rather than "this".
e.g.
(function(){
// private constructor that is only accessable by your plugin.
function _Plugin(elements, args){
// do stuff
}
_Plugin.prototype.customFunctionCallWithinPlugin = function(){
// do more stuff
};
$.fn.Plugin = function(args){
return new _Plugin(this, args);
};
})();
EDIT: Alex beat me to it.
精彩评论