Why jQuery UI Uses the Widget Factory
Writing a jQuery plugin is as simple as adding a method to jQuery.prototype(usually shown as $.fn) and following a few simple rules, such as returning this. So why does the Widget Factory exist?
In this chapter, we will explain the benefits of the Widget Factory, and learn when and why to use it.
Stateless vs. Stateful Plugins
Most jQuery plugins are stateless; they perform an action and their task is done. For example, if you use .text( "hello" ) to set an element's text, there is no installation phase and the result is always the same. This type of plugin 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 lot of specialized code for initialization and state management (and sometimes destruction). This leads to boilerplate templates for creating stateful plugins. Worse still, each plugin author manages the plugin lifecycle and state in a different way, resulting in different API styles across plugins. The Widget Factory is designed to solve these problems by removing the boilerplate and creating a consistent API for plugins.
A Consistent API
The Widget Factory defines how to create and destroy widgets, get and set options, call methods, and listen for events triggered by widgets. By using the Widget Factory to create stateful plugins, they automatically conform to the defined standard, making it easier for new users to use your plugin. In addition, the Widget Factory enables the definition of interfaces. If you are not yet familiar with the API provided by the Widget Factory, see How to Use the Widget Factory。
Setting Options at Initialization
When you create a widget that accepts options, you should define defaults for as many options as possible. Then, at initialization, merge the options provided by the user with the defaults. You can also expose the defaults so 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 provides this as well and improves upon it. With the Widget Factory, it looks 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.
}
});