Latest web development tutorials

How to use jQuery UI widget library

We will create a progress bar. As shown in the following examples, which by calling jQuery.widget() to complete, it takes two parameters: a plug-in name is to be created, a text that contains the object is a function of plug-in support. When the plug is called, it creates a new plug-in instance, all functions will be executed in the context of this example. This two important ways different standard jQuery plugin. First, the context is an object, not a DOM element. Secondly, the context is always a single object, not a collection.

$.widget( "custom.progressbar", {
    _create: function() {
        var progress = this.options.value + "%";
        this.element
            .addClass( "progressbar" )
            .text( progress );
    }
});

Must contain the name of the plugin namespace, in this example, we use a custom namespace. You can only create one layer deep namespace, therefore, custom.progressbar is an effective plug-in name, very.custom.progressbar not a valid plug-in name.

We saw parts library (Widget Factory) provides us with two properties. this.element is a jQuery object containing one element. If we call the plug-in jQuery object that contains multiple elements, it will create a separate plug-in instance for each element, and each instance will have its own this.element . The second property, this.options , is a plug-in options include all the key name / value pairs hash (hash). These options can be passed to plug-in, as follows:

$( "<div></div>" )
    .appendTo( "body" )
    .progressbar({ value: 20 });

When we call jQuery.widget() , which by giving jQuery.fn (used to create a standard plug-in system) add the function to extend jQuery. Function name is added based on your pass jQuery.widget() name without the namespace - "progressbar". Plug-pass option is to obtain the value set in the plugin instance. As shown in the following example, we can specify a default value to any option. When designing your API, you should be aware of the most common use of your plug-in, so you can set the appropriate default, and ensure that all options truly optional.

$.widget( "custom.progressbar", {
 
    // Default options.
    options: {
        value: 0
    },
    _create: function() {
        var progress = this.options.value + "%";
        this.element
            .addClass( "progressbar" )
            .text( progress );
    }
});

Call the plug-in methods

Now we can initialize our progress bar, we will perform an action by calling the method on the plug-in instance. To define a plug-in method, we only we pass jQuery.widget() reference to a function object. We can also define "private" method to the function name with an underscore prefix.

$.widget( "custom.progressbar", {
 
    options: {
        value: 0
    },
 
    _create: function() {
        var progress = this.options.value + "%";
        this.element
            .addClass( "progressbar" )
            .text( progress );
    },
 
    // Create a public method.
    value: function( value ) {
 
        // No value passed, act as a getter.
        if ( value === undefined ) {
            return this.options.value;
        }
 
        // Value passed, act as a setter.
        this.options.value = this._constrain( value );
        var progress = this.options.value + "%";
        this.element.text( progress );
    },
 
    // Create a private method.
    _constrain: function( value ) {
        if ( value > 100 ) {
            value = 100;
        }
        if ( value < 0 ) {
            value = 0;
        }
        return value;
    }
});

To invoke a method on a plug-in instance, you can pass the name of the method to the jQuery plugin. If you call a method to accept parameters, you simply pass the method name behind these parameters.

Note: The jQuery function is passed to the same method name used to initialize the plug-in to perform the method. This is done to prevent the jQuery namespace pollution while maintaining the chain method calls. In the subsequent chapters, we will see other uses look more natural.

var bar = $( "<div></div>" )
    .appendTo( "body" )
    .progressbar({ value: 20 });
 
// Get the current value.
alert( bar.progressbar( "value" ) );
 
// Update the value.
bar.progressbar( "value", 50 );
 
// Get the current value again.
alert( bar.progressbar( "value" ) );

Use the options

option() method is automatically provided to the plug-in. option() method allows you to get and set options after initialization. The method as jQuery's .css() and .attr() method: You can only pass a name as the argument is to use, you can also pass a name and value as set using or passing a key name / value pairs hash to set multiple values. When used as a value, a plug-in returns the name of the incoming option corresponding current value. When used as a setter, widget _setOption method will be called for each option is set. We can specify a plug-in in our _setOption method to reflect the options change. Change the options for action to be performed independently, we can override _setOptions .

$.widget( "custom.progressbar", {
    options: {
        value: 0
    },
    _create: function() {
        this.options.value = this._constrain(this.options.value);
        this.element.addClass( "progressbar" );
        this.refresh();
    },
    _setOption: function( key, value ) {
        if ( key === "value" ) {
            value = this._constrain( value );
        }
        this._super( key, value );
    },
    _setOptions: function( options ) {
        this._super( options );
        this.refresh();
    },
    refresh: function() {
        var progress = this.options.value + "%";
        this.element.text( progress );
    },
    _constrain: function( value ) {
        if ( value > 100 ) {
            value = 100;
        }
        if ( value < 0 ) {
            value = 0;
        }
        return value;
    }
});

Add callback

The simplest extension is to add a callback so that users can react when changes occur in the plug-in state. We can look at the following example of how to add a callback to the progress bar when the progress bar reaches 100 percent. _trigger() method takes three arguments: the name of the callback, a callback jQuery event started objects, and a hash of the data associated with the event. Callback name is the only one required parameter, but want to implement custom features users on plug-in, the other parameters are very useful. For example, if we create a draggable plugin, we can pass mousemove drag event when triggered the callback, which will allow users to respond to the event based on the object provided by the x / y coordinates of the drag. Please note passed to _trigger() of the original event must be a jQuery event instead of a native browser events.

$.widget( "custom.progressbar", {
    options: {
        value: 0
    },
    _create: function() {
        this.options.value = this._constrain(this.options.value);
        this.element.addClass( "progressbar" );
        this.refresh();
    },
    _setOption: function( key, value ) {
        if ( key === "value" ) {
            value = this._constrain( value );
        }
        this._super( key, value );
    },
    _setOptions: function( options ) {
        this._super( options );
        this.refresh();
    },
    refresh: function() {
        var progress = this.options.value + "%";
        this.element.text( progress );
        if ( this.options.value == 100 ) {
            this._trigger( "complete", null, { value: 100 } );
        }
    },
    _constrain: function( value ) {
        if ( value > 100 ) {
            value = 100;
        }
        if ( value < 0 ) {
            value = 0;
        }
        return value;
    }
});

Callback function essentially just an additional option, so you can get the same as the other options and set them. Whenever callback, there will be a corresponding event is triggered. Event type is by name and the name of the callback function to determine the connection plug. Callback and event accept the same two arguments: an event object and a hash of the data associated with the event, particularly as shown in the following examples. You may need to include a plug-in features to prevent users, in order to do this, the best way is to create love you may revoke callbacks. Users can revoke callback or an event related to a native revoke any event with them, they are by calling event.preventDefault() or return false to achieve. If you revoke callback, _trigger() method will return false , so you can achieve the appropriate function in the plug-ins.

var bar = $( "<div></div>" )
    .appendTo( "body" )
    .progressbar({
        complete: function( event, data ) {
            alert( "Callbacks are great!" );
        }
    })
    .bind( "progressbarcomplete", function( event, data ) {
        alert( "Events bubble and support many handlers for extreme flexibility." );
        alert( "The progress bar value is " + data.value );
    });
 
bar.progressbar( "option", "value", 100 );

Nature

Now we have seen how to use the widget library (Widget Factory) to create a plug-in, let's look at how it actually works. When you call jQuery.widget() , it creates a constructor function for the plug-in and set your plugin instance is passed as a prototype object. All functions are automatically added to the widget comes from a basic widget a prototype, defined as jQuery.Widget.prototype . When you create a plug-in instance will be used jQuery.data stores it on the original DOM element, plug-in name as the key name.

Since the plugin instance directly linked to the DOM element, you can directly access the plug-in instance, without the need to traverse the plug-in methods. This method will allow you to call directly on the plug-in instance, without the need to pass a string method name, and you can also access properties directly plug.

var bar = $( "<div></div>" )
    .appendTo( "body" )
    .progressbar()
    .data( "progressbar" );
 
// Call a method directly on the plugin instance.
bar.option( "value", 50 );
 
// Access properties on the plugin instance.
alert( bar.options.value );

You can also create an instance of the plug-in without traversal methods, and the option to call the constructor elements directly:

var bar = $.custom.progressbar( {}, $( "<div></div>" ).appendTo( "body") );
 
// Same result as before.
alert( bar.options.value );

Extension of the prototype

Widget constructors and prototypes biggest advantage is easy extensions. By adding or modifying the method plug prototype, we can modify the widget behavior of all instances. For example, if we want to add a method to the progress bar to reset to 0% progress, we can add this method to the prototype, which will be called on all plug-in instance.

$.custom.progressbar.prototype.reset = function() {
    this._setOption( "value", 0 );
};

For extended widgets for more details and how to create a new widget on an existing widget more details, see the extended widget (Widget) by member libraries (the Widget Factory's) .

Clear up

In some cases, the application allows the user to plug-ins, and then cancel the application. You can _destroy() to do this method. In _destroy() within a method, you should revoke all action during initialization and post-use plug-ins do. _destroy() by .destroy() method is called, .destroy() method is a plug-in instances when removing an element from the DOM bindings called automatically, so it can be used for garbage collection. Basic .destroy() method is also commonly used to deal with some cleanup operations, such as removing the DOM element from the widget instance cited, unbind widget namespace all events from the elements, use unbind all _bind() add events.

$.widget( "custom.progressbar", {
    options: {
        value: 0
    },
    _create: function() {
        this.options.value = this._constrain(this.options.value);
        this.element.addClass( "progressbar" );
        this.refresh();
    },
    _setOption: function( key, value ) {
        if ( key === "value" ) {
            value = this._constrain( value );
        }
        this._super( key, value );
    },
    _setOptions: function( options ) {
        this._super( options );
        this.refresh();
    },
    refresh: function() {
        var progress = this.options.value + "%";
        this.element.text( progress );
        if ( this.options.value == 100 ) {
            this._trigger( "complete", null, { value: 100 } );
        }
    },
    _constrain: function( value ) {
        if ( value > 100 ) {
            value = 100;
        }
        if ( value < 0 ) {
            value = 0;
        }
        return value;
    },
    _destroy: function() {
        this.element
            .removeClass( "progressbar" )
            .text( "" );
    }
});

Close notes

Component Library (Widget Factory) is a way to create a state for the plug. There are other different models can be used, and each has its own advantages and disadvantages. Component Library (Widget Factory) solves many common problems, and greatly improves the efficiency, but also greatly enhance the reusability of the code, making it suitable for jQuery UI and other state of the plug-ins.

Note that in this section we use the custom namespace. ui namespace is reserved official jQuery UI plugin. When creating your own plug-ins, you should create your own namespace. So as to more clearly from where plug, which belongs to the range.