jQuery UI Why Use the Widget Factory

Writing a jQuery plugin is as simple as adding a method tojQuery.prototype(usually shown as$.fn) adding a method is just as simplethis. 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 some action and that completes their task. For example, if you use.text( "hello" )to set the text of an element, there is no installation phase, and the result is always 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 led to templates for creating stateful plugins. Worse, each plugin author manages the plugin lifecycle and state differently, resulting in different API styles across plugins. The Widget Factory aims to solve these problems by removing the template and creating a consistent API for plugins.

Consistent API

The Widget Factory defines how to create and destroy widgets, get and set options, call methods, and listen to events triggered by widgets. By using the Widget Factory to create stateful plugins, you automatically conform to defined standards, making it easier for new users to use your plugin. In addition, the Widget Factory can also implement defined interfaces. If you are not familiar with the API provided by the Widget Factory, please check outHow 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 users can change the default values. A common pattern in jQuery plugins is as follows:

$.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 would 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.
    }
 
});
Other Extensions