Writing jQuery Plugins using OOP [closed]
I was wondering what's the current "state-of-the-art" to write a jQuery Plugins. I read a lot of different approaches and I don't know which one fits best.
Can you recommondation usefull links/templates for writing jQuery Plugins using OOP.
Thanks
the basic rules are:
Don't clutter the jQuery namespace with your code - there should only be one method per plugin added to root of the jQuery object or to
jQuery.fn
Use an immediately executing anonymous funciton to ensure the code is run just once
Pass in the jQuery object as a parameter with the identifier
$
, can safely use the$
in this scope then :)REMEMBER when you add a new method to
jQuery.fn
,this
is bound to a jQuery wrapped set, you don't have to wrap it again!use
this.each
to loop through all matched elementsreturn
this
from your plugin to enable chainability (unless of course your plugin returns a distinct value)allow options to be passed in and overlayed over some default object (which you also expose to be overriden)
allow for defaults to be re-set by user for global changes
(function($) { //see point 3 var defaults = { someDefaultValues : "value" }; $.fn.myPlugin = function(options) { // see point 1, only 1 method var settings = $.extend({}, defaults, options); //see point 7 this.each(function() { //see point 5 var currentElement = $(this); //"this" now refers to current DOM element //put bulk of logic here }); return this; //see point 6 }; //see point 8, enables users to completely override defaults, rather than per call via options $.fn.myPlugin.defaults = defaults; })(jQuery); //see point 2
see the jQuery docs for a good guide, they go into more advanced details considering how you might want to execute more than one method per plugin, plus storing data on elements and other things. Most of the stuff i have
Two links/templates I refer to are Stefan Gabos jQuery Plugin Boilerplate and Oscar Godson's jQuery Plugin Skeleton
I'm not claiming they're "state of the art" but they've served me very well.
精彩评论