Patterns
jQuery plug-ins have few concrete rules, which is one of the
reasons for the incredible diversity in how they are implemented across
the community. At the most basic level, we can write a plug-in simply by
adding a new function property to jQuery’s jQuery.fn object, as follows:
$.fn.myPluginName=function(){// our plugin logic};
This is great for compactness, but the following would be a better foundation to build on:
(function($){$.fn.myPluginName=function(){// our plugin logic};})(jQuery);
Here, we’ve wrapped our plug-in logic in an anonymous function. To
ensure that our use of the $ sign as a
shorthand creates no conflicts between jQuery and other JavaScript
libraries, we simply pass it to this closure, which maps it to the dollar
sign. This ensures that it can’t be affected by anything outside of its
scope of execution.
An alternative way to write this pattern would be to use jQuery.extend(), which enables us to define
multiple functions at once and sometimes make more sense
semantically:
(function($){$.extend($.fn,{myplugin:function(){// your plugin logic}});})(jQuery);
We have now reviewed some jQuery plug-in fundamentals, but a lot more could be done to take this further. A Lightweight Start is the first complete plug-in design pattern we’ll be exploring, and it covers some best practices that we can use for basic everyday plug-in development, taking into account common gotchas worth applying.
Note
While most of the patterns below will be explained, ...