After coming across a recent blog post on jQuery Plugin Boilerplate code it reminded me a few months back when I was looking at the best method for authoring plugins for use at work. After much googling and trial and error I finally came to grips with something and below is the end result.
The code in the jQuery Plugin Boilerplate blog post is very similar to the plugin authoring page in the jQuery Documentation. While they are both good resources, I think they favor single plugins and may potentially lead developers down a path of duplicate code. Similar to jQuery UI’s $.widget what I want to push here is a snippet of code that can transform your code into a “jQuery Plugin” (is there a real definition of this somewhere?).
The Meat - Pluginifier (Instantiator)
The plugin instantiator function creates the prototype plugin function using jQuery.fn, inside that function the code will handle creating/storing/retrieving plugin instances and calling methods on plugins that are already created. This code is meant for reuse for n amount of plugins you create, there is no need to rewrite this block of code (or something similar) for each plugin you have.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
The Cheese - Plugin Boilerplate
The idea of this plugin boilerplate is that you keep the code that does everything separate from the code that makes it accessible as a jQuery Plugin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
The pickles?
These two jsFiddles are examples of the same plugin written with and without the pluginifier and my boilerplate. You’ll see that the functionality stays the same and the concept to grasp here is on code reuse and management. - Also note there is overhead in filesize when you are dealing with a single plugin, however once you add another plugin that utilizes $.pluginifier you gain a few bytes.
All of this code is available on github: https://github.com/aknosis/jquery-pluginifier/.
I’m interested to see how people may use this code or what else they use instead. Questions and comments are always welcomed. Alex Sexton deserves most of the credit for this cod (see below).
Resources:
- Using Inheritance Patterns to Organize Large jQuery Applications - If you want a greater understanding of this concept take a look at Alex Sexton’s post, you will see where I came up with most of this code (although there are some tweaks that I made for personal preference), read the comments too as there is some good discussion.
- jQuery Plugin Boilerplate - Stefan Gabos
- jQuery Documentation on Plugin Authoring