Why Use the Widget Factory in jQuery UI
Writing a jQuery plugin is as simple as adding a method to jQuery.prototype
(commonly displayed as $.fn
), and it requires following some simple rules, such as returning this
. So why does the Widget Factory exist?
In this section, we will discuss the benefits of the Widget Factory and understand when and why to use it.
Stateless vs. Stateful Plugins
Most jQuery plugins are stateless; they perform some actions and complete their tasks. For example, if you use .text("hello")
to set an element's text, there is no setup phase, and the result is the same. For this type of plugin, it simply extends jQuery's prototype.
However, some plugins are stateful; they have a full lifecycle, maintain state, and react to changes. These plugins require a significant amount of specialized code for initialization and state management (and sometimes destruction). This leads to the emergence of templates for creating stateful plugins. Worse, each plugin author manages the plugin's lifecycle and state differently, resulting in different plugins having different API styles. The Widget Factory aims to solve these issues by removing the template and providing a consistent API for plugin creation.
Consistent API
The Widget Factory defines how to create and destroy widgets, get and set options, call methods, and listen to events triggered by the widget. By using the Widget Factory to create stateful plugins, they automatically conform to the defined standards, making it easier for new users to use your plugins. Additionally, the Widget Factory allows for the definition of interfaces. If you are not familiar with the API provided by the Widget Factory, please refer to How to Use the Widget Factory.
Setting Options at Initialization
When you create a plugin that accepts options, you should define defaults for as many options as possible. Then, at initialization, merge the user-provided options with the defaults. You can also expose the defaults so that users can change the default values. In jQuery plugins, a common pattern looks like this:
$.fn.plugin = function(options) {
options = $.extend({}, $.fn.plugin.defaults, options);
// Plugin logic goes here.
};
$.fn.plugin.defaults = {
param1: "foo",
param2: "bar",
param3: "baz"
};
The Widget Factory also provides this functionality and improves upon it. After using the Widget Factory, it will look like this:
$.widget("ns.plugin", {
// Default options.
options: {
param1: "foo",
param2: "bar",
param3: "baz"
},
_create: function() {
// Options are already merged and stored in this.options
// Plugin logic goes here.
}
});