jQuery UI Why Use Widget Library


Writing a jQuery plug-in is as easy as adding a method to jQuery.prototype (usually shown as $.fn) and requires following a few simple rules, such as returning this. So why does a widget factory exist?

In this chapter, we will explain 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 to complete their tasks. For example, if you use .text( "hello" ) to set the text of an element, the result will be the same without the installation phase. For this type of plugin, it just extends jQuery's prototype.

However, some plug-ins are stateful, they have a full life cycle, 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 templates for creating stateful plugins. To make matters worse, each plug-in author manages the life cycle and status of the plug-in in different ways, which results in different plug-ins having different API styles. The Widget Factory aims to solve these problems by removing templates 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 plug-ins, they automatically conform to defined standards, making it easier for new users to use your plug-ins. In addition, the Widget Factory can also implement the function of defining interfaces. If you are not familiar with the API provided by Widget Factory, please check out How to use Widget Factory.

Setting options on initialization

When you create a plugin that accepts options, you should define defaults for as many options as possible. Then during initialization, the user-provided options are merged with defaults. You can also expose defaults so users can change the defaults. In jQuery plug-ins, a commonly used pattern 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 library (Widget Factory) also provides this function and has made improvements on 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.
    }
 
});