Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Why the jQuery UI uses part libraries


May 08, 2021 jQuery UI


Table of contents


Why jQuery UI uses Widget Factory

Writing a jQuery plug-in is as easy as adding a method to jQuery.prototype (usually shown as $.fn and requires some simple rules, such as this So why is there a Widget Factory?

In this section, we'll explain the benefits of widget Factory and learn when to use it and why.

Stateless vs. State plug-in

Most jQuery plug-ins are stateless, and they perform some actions to accomplish their tasks. F or example, if you .text( "hello" ) the text of an element without an installation phase, the results are the same. For this type of plug-in, it just extends the prototype of jQuery.

However, some plug-ins are state- and have full lifecycles, maintained states, and react to change. T hese plug-ins require a lot of specialized code to initialize and state management (sometimes destroyed). T his results in a template for creating a stated plug-in. T o make matters worse, the authors of each plug-in manage the lifecycle and state of the plug-in in different ways, which results in different plug-ins with different API styles. The Widget Factory is designed to address these issues by removing the template and creating a consistent API for the plug-in.

Consistent APIs

Widget Factory defines how widgets are created and destroyed, get and set options, call methods, and listen for events triggered by widgets. C reating a stateable plug-in by using the Widget Factory automatically meets defined criteria, making it easier for new users to use your plug-in. I n addition, the Widget Factory enables the function of defining interfaces. If you're not familiar with the APIs provided by the Widget Factory, check out How to use the Widget Factory.

Set options at initialization

When you create a plug-in that accepts options, you should define defaults for as many options as possible. T hen, at initialization, combine the user-provided options with defaults. Y ou can also expose defaults so that users can change the default values. In the jQuery plug-in, 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"
};

Widget Factory also provides this feature and has made improvements to it. When you use 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.
    }
 
});