I am building a rather large web application and have built a handful of plugins using the classic plugin pattern. Some of these exceed 50 lines and maintain state. I recently discovered jQuery UI's widget factory, and it appears if I were to convert my plugins to the this style, the code would be easier to read and maintain. Other than time and effort, I'm trying to determine if there's a downside an converting them over. I already use jQuery UI for some other plugins.
To start, we'll create a progress bar that just lets us set the progress once. As we can see below, this is done by calling jQuery. widget() with two parameters: the name of the plugin to create, and an object literal containing functions to support our plugin.
a jQuery UI widget is a specialized jQuery plug-in. Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in's lifetime.
The widget factory defines how to create and destroy widgets, get and set options, invoke methods, and listen to events triggered by the widget. By using the widget factory to build your stateful plugins, you are automatically conforming to a defined standard, making it easier for new users to start using your plugins.
A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.
Walk through these slides: http://ajpiano.com/widgetfactory/
They'll give you a fantastic overview of the widget factory, why you should be using it, and how.
I've decided to convert one of the more complex stateful plugins to use the jQuery widget factory. There was a bit of a learning curve, I believe the benefits justified the work. While I'm not leveraging theme roller support, here are some of the other benefits I found useful:
Obviously, you can achieve all of these with the traditional plugin pattern. But the code appears much cleaner to my eye and will be much easier to maintain in the longer term. Many thanks to Eric Hynds and his MuliSelect Widget for providing source code for me to study and learn how to use the Widget Factory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With