Latest web development tutorials

Why use jQuery UI widget library

Write jQuery plug-ins and to jQuery.prototype (usually displayed as $.fn ) Add Method as simple and need to follow some simple rules, such as the return to this . So why would the presence of component libraries (Widget Factory)?

In this section, we will explain the benefits of component libraries (Widget Factory), and learn when to use it, and why to use it.

Stateless vs. Stateful widget

Most jQuery plugins are stateless, they perform some action to complete their task. For example, if you use .text( "hello" ) element is set to the text, there is no installation phase, the results are the same. For this type of plug-in, it just extends the jQuery prototype.

However, some plug-ins are stateful, they have the whole life cycle, to maintain the status and response to change. These plug-ins require a lot of specialized code to initialize and state management (and sometimes destroy). This led to the emergence of plug-ins for creating stateful template. Worse, each widget authors in different ways to manage plug-in life cycle and the state, which led to a different plug-ins have different API styles. Component Library (Widget Factory) is intended to address these issues, it removes the template and create a consistent API for plug-ins.

Consistent API

Component Library (Widget Factory) defines how to create and destroy widgets, get and set options, call the method, as well as monitor widget trigger events. To create stateful plugin using the widget library (Widget Factory), automatically meets the definition of standards, allowing new users to more easily use your plug-in. In addition, the widget library (Widget Factory) function also enables the definition of the interface. If you are part of the API library (Widget Factory) provided not familiar with, check out how to use the library member (Widget Factory) .

Set options in the initialization

When you create a plug-in options to accept, you should be as many options define the defaults. Then in the initialization, to provide users with the option of merging with defaults. You can also expose defaults, so that users can change the default value. In jQuery plug-in, a common mode 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"
};

Component Library (Widget Factory) also offers this feature, and improvements have been made in it. After using the widget library (Widget Factory), it will be shown below.

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