jQuery UI API - Widget Factory
Category
jQuery.widget( name [, base ], prototype ) Usage
Description:Create stateful jQuery plugins using the same abstraction as all jQuery UI widgets.
| Parameters | Type | Type |
|---|---|---|
| name | String | The name of the widget to create, including the namespace. |
| base | Function() | The base widget to inherit from. Must be a constructor that can be instantiated with the `new` keyword. Defaults to jQuery.Widget. |
| prototype | PlainObject | The object to use as the widget prototype. |
You can use$.Widgetan object as the base to inherit from, or you can explicitly create a new widget from scratch based on an existing jQuery UI or third-party control. Defining a widget with the same name to inherit the base widget even allows you to extend the widget appropriately.
jQuery UI contains many stateful widgets, so the usage pattern is slightly different from typical jQuery plugins. All jQuery UI widgets use the same pattern, defined by the Widget Factory. So once you learn to use one, you know how to use the other widgets.
Note: This chapter uses theProgressbar Widgetas a demonstration example, but the syntax applies to every widget.
Initialization
In order to track the state of the widget, we must introduce the full lifecycle of the widget. The lifecycle begins when the widget is initialized. To initialize a widget, we simply call the plugin on one or more elements.
$( "#elem" ).progressbar();
This initializes each element in the jQuery object. In the example above, the element id is `progressbar`."elem"。
Options
Becauseprogressbar()it is called without arguments, the widget is initialized with default options. We can pass a set of options at initialization to override the default options:
$( "#elem" ).progressbar({ value: 20 });
We can pass as many options as needed, and any options we do not pass use their default values.
You can pass multiple option arguments, which will be merged into a single object (similar to$.extend( true, target, object1, objectN )`$.extend`). This is useful for overriding some settings for all instances and sharing options between instances:
var options = { modal: true, show: "slow" };
$( "#dialog1" ).dialog( options );
$( "#dialog2" ).dialog( options, { autoOpen: false });
All options passed at initialization are deep copied, ensuring that objects can be modified later without affecting the widget. Arrays are the only exception; they are referenced as-is. This exception is to properly support data binding, where the data source must be a reference.
Default values are stored in the widget's properties, so we can override the values set by jQuery UI. For example, after the following setting, all future progressbar instances will default to a value of 80:
$.ui.progressbar.prototype.options.value = 80;
Options are an integral part of the widget's state, so we can also set options after initialization. We will see the option method later.
Methods
Now that the widget has been initialized, we can query its state or perform actions on the widget. All actions after initialization are performed by calling methods. To call a method on the widget, we pass the method name to the jQuery plugin. For example, to call thevalue()`value` method, we can use:
$( "#elem" ).progressbar( "value" );
If a method accepts parameters, we can pass them after the method name. For example, to pass the parameter `2` to the40tovalue()`value` method, we can use:
$( "#elem" ).progressbar( "value", 40 );
Like other methods in jQuery, most widget methods return the jQuery object:
$( "#elem" ) .progressbar( "value", 90 ) .addClass( "almost-done" );
Each widget has its own set of methods based on the functionality provided by the widget. However, there are some methods that exist on all widgets, which are explained in detail below.
Events
All widgets have events associated with their various behaviors to notify you when state changes. For most widgets, when an event is triggered, its name is prefixed with the lowercase form of the widget name. For example, we can bind the progressbar'schange`change` event, which is triggered when the value changes.
$( "#elem" ).bind( "progressbarchange", function() {
alert( "The value has changed!" );
});
Each event has a corresponding callback, which is available as an option. If needed, we can hook into the progressbar'schange`change` callback instead of bindingprogressbarchangethe `change` event.
$( "#elem" ).progressbar({
change: function() {
alert( "The value has changed!" );
}
});
All widgets have achange`create` event, which is triggered upon instantiation.
Instantiation
The widget instance is stored using the widget's full name as the key injQuery.data()`data`. Therefore, you can use the following code to retrieve the instance object of the Progressbar Widget from an element.
$( "#elem" ).data( "ui-progressbar" );
Whether an element is bound to a given widget can be detected using the:data`:ui-progressbar` selector.
$( "#elem" ).is( ":data( 'ui-progressbar' )" ); // true $( "#elem" ).is( ":data( 'ui-draggable' )" ); // false
You can also use:datato obtain a list of all elements that are instances of a given widget.
$( ":data( 'ui-progressbar' )" );
Properties
All widgets have the following properties:
- defaultElement`defaultElement`: The element to use when no element was provided when constructing the widget instance. For example, since the progressbar's
defaultElementYes"<div>",$.ui.progressbar({ value: 50 })`defaultElement` is a newly created<div>`div`, you can instantiate a progressbar widget instance without passing an element. - document`document`: The document that contains the widget's element.
documentUseful if you need to interact with the widget within an iframe. - element`element`: A jQuery object containing the element used to instantiate the widget. If you select multiple elements and call
.myWidget()`.progressbar()`, a separate widget instance will be created for each element. Therefore, this property always contains one element. - namespace`namespace`: The location in the global jQuery object where the widget prototype is stored. For example,
"ui"ofnamespace`$.ui.draggable` indicates that the widget prototype is stored in$.ui。 - options`$.ui.draggable`. `options`: An object containing the options currently used by the widget. At instantiation, any user-provided options will automatically be merged with
$.myNamespace.myWidget.prototype.optionsthe default values defined in the widget prototype. User-specified options override the defaults. - uuid`uuid`: A unique integer representing the widget identifier.
- version`version`: The string version of the widget. For jQuery UI widgets, this property is set to the version of jQuery UI used by the widget. Plugin developers must explicitly set this property in their prototypes.
- widgetEventPrefix`widgetEventPrefix`: The prefix added to the widget's event names. For example,the Draggable Widgetof
widgetEventPrefixYes"drag", so when creating a draggable, the event name is"dragcreate"`dragcreate`. By default, the widget'swidgetEventPrefix`widgetEventPrefix` is its name.Note: This property has been deprecated and will be removed in future versions. Event names will be changed to widgetName:eventName (for example `progressbarcreate`)."draggable:create")。 - widgetFullName`widgetFullName`: The full name of the widget, including the namespace. For
$.widget( "myNamespace.myWidget", {} ),widgetFullNamethe progressbar, this will be `ui-progressbar`."myNamespace-myWidget"。 - widgetName`name`: The name of the widget. For
$.widget( "myNamespace.myWidget", {} ),widgetNamethe progressbar, this will be `progressbar`."myWidget"。 - window`window`: The window that contains the widget's element.
windowUseful if you need to interact with the widget within an iframe.
jQuery.Widget Base Widget Usage
Description:The base widget used by the Widget Factory.
Quick Navigation
| Options | Methods | Events |
|---|---|---|
| Options | Type | Description | Default |
|---|---|---|---|
| disabled | Boolean | If set totrue`true`, the widget is disabled.Code examples: Initialize a widget with the specified
$( ".selector" ).widget({ disabled: true });
Get or set the // getter var disabled = $( ".selector" ).widget( "option", "disabled" ); // setter $( ".selector" ).widget( "option", "disabled", true ); |
false |
| hide | Boolean or Number or String or Object | Whether and how to use animation to hide the element. Multiple types are supported:
Code examples: Initialize the widget with the specified
$( ".selector" ).widget({ hide: { effect: "explode", duration: 1000 } });
After initialization, get or set the
// getter
var hide = $( ".selector" ).widget( "option", "hide" );
// setter
$( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } );
|
null |
| show | Boolean or Number or String or Object | Whether to display the element with an animation, and how to animate the display. Supports multiple types:
Code examples: Initialize the widget with the specified
$( ".selector" ).widget({ show: { effect: "blind", duration: 800 } });
After initialization, get or set the
// getter
var show = $( ".selector" ).widget( "option", "show" );
// setter
$( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } );
|
null |
| Methods | Returns | Description |
|---|---|---|
| _create() | jQuery (plugin only) | _create()method is the widget's constructor. It takes no arguments, butthis.elementandthis.optionsis already set.
Code examples: Sets the background color of the widget element based on an option.
_create: function() {
this.element.css( "background-color", this.options.color );
}
|
| _delay( fn [, delay ] ) | Number | Calls the provided function after the specified delay. Maintainsthisthe correct context. EssentiallysetTimeout()。uses clearTimeout()returns the timeout ID.
Code examples: After 100 milliseconds, on the widget, call the this._delay( this._foo, 100 ); |
| _destroy() | jQuery (plugin only) | The publicdestroy()method clears all public data, events, etc. It represents the custom, widget-specific cleanup._destroy()。
Code examples: Removes a class from the widget's element when the widget is destroyed.
_destroy: function() {
this.element.removeClass( "my-widget" );
}
|
| _focusable( element ) | jQuery (plugin only) | Establishes, when focusing on an element, theui-state-focusclass to be applied.element。
Code examples: Applies focusable styling to a group of elements within the widget: this._focusable( this.element.find( ".my-items" ) ); |
| _getCreateEventData() | Object | All widgets triggercreateevents. By default, no data is provided in the event, but this method returns an object that is passed ascreateevent data.
Code examples: toward
_getCreateEventData: function() {
return this.options;
}
|
| _getCreateOptions() | Object | This method allows the widget to define a custom method for defining options during initialization. User-provided options override the options returned by this method, i.e., they override the default options.
Code examples: Makes the id attribute of the widget's element available as an option.
_getCreateOptions: function() {
return { id: this.element.attr( "id" ) };
}
|
| _hide( element, option [, callback ] ) | jQuery (plugin only) | Hides an element using a built-in animation method or a custom effect. For possibleoptionvalues, seehide。
Code examples: Passes
this._hide( this.element, this.options.hide, function() {
// Remove the element from the DOM when it's fully hidden.
$( this ).remove();
});
|
| _hoverable( element ) | jQuery (plugin only) | Establishes, when hovering over an element, theui-state-hoverclass to be applied.element. Event handlers are automatically cleaned up on destroy.
Code examples: When hovering over the element, to all elements within the element, this._hoverable( this.element.find( "div" ) ); |
| _init() | jQuery (plugin only) | The concept of widget initialization is different from creation. Whenever the plugin is called without arguments or with only an options hash, the widget is initialized. This method is included when the widget is created. Note: If there are logical actions to be performed when the widget is successfully called without arguments, initialization can only be handled at this time.
Code examples: If the
_init: function() {
if ( this.options.autoOpen ) {
this.open();
}
}
|
| _off( element, eventName ) | jQuery (plugin only) | Unbinds event handlers from the specified element.
Code examples: Unbinds all click events from the widget's element. this._off( this.element, "click" ); |
| _on( [suppressDisabledCheck ] [, element ], handlers ) | jQuery (plugin only) | Delegation via selectors within the event name is supported, for example"click .foo"。_on()The method provides several benefits over direct event binding:
Code examples: Prevents the default behavior of all clicked links within the widget element.
this._on( this.element, {
"click a": function( event ) {
event.preventDefault();
}
});
|
| _setOption( key, value ) | jQuery (plugin only) | For each individual option, calls the_setOptions()method. The widget state is updated as changes are made.
Code examples: When the widget's
_setOption: function( key, value ) {
if ( key === "width" ) {
this.element.width( value );
}
if ( key === "height" ) {
this.element.height( value );
}
this._super( key, value );
}
|
| _setOptions( options ) | jQuery (plugin only) | When theoption()method is called, regardless of the form in which it is calledoption(). If you need to change processor-intensive handlers based on multiple option changes, overriding this method is useful.
Code examples: If the widget's
_setOptions: function( options ) {
var that = this,
resize = false;
$.each( options, function( key, value ) {
that._setOption( key, value );
if ( key === "height" || key === "width" ) {
resize = true;
}
});
if ( resize ) {
this.resize();
}
}
|
| _show( element, option [, callback ] ) | jQuery (plugin only) | Shows an element using a built-in animation method or a custom effect. For possibleoptionvalues, seeshow。
Code example: Pass a custom animation
this._show( this.element, this.options.show, function() {
// Focus the element when it's fully visible.
this.focus();
}
|
| _super( [arg ] [, ... ] ) | jQuery (plugin only) | Calls the method of the same name on the parent widget, with any specified arguments. Essentially,.call()。
Code example: Handle
_setOption: function( key, value ) {
if ( key === "title" ) {
this.element.find( "h3" ).text( value );
}
this._super( key, value );
}
|
| _superApply( arguments ) | jQuery (plugin only) | Calls the method of the same name on the parent widget, with an array of arguments. Essentially,.apply()。
Code example: Handle
_setOption: function( key, value ) {
if ( key === "title" ) {
this.element.find( "h3" ).text( value );
}
this._superApply( arguments );
}
|
| _trigger( type [, event ] [, data ] ) | Boolean | Trigger an event and its associated callback. The option with that name is equivalent to the type called as the callback. The event name is a lowercase string of the widget name and the type. Note: When data is provided, you must provide all three parameters. If no event is passed, pass If the default behavior is prevented, it returns
Code example: When a key is pressed, trigger the
this._on( this.element, {
keydown: function( event ) {
// Pass the original event so that the custom search event has
// useful information, such as keyCode
this._trigger( "search", event, {
// Pass additional information unique to this event
value: this.element.val()
});
}
});
|
| destroy() | jQuery (plugin only) | Completely remove the widget functionality. This returns the element to its pre-initialization state.
Code example: Destroy the widget when any anchor of the widget is clicked.
this._on( this.element, {
"click a": function( event ) {
event.preventDefault();
this.destroy();
}
});
|
| disable() | jQuery (plugin only) | Disable the widget.
Code example: Disable the widget when any anchor of the widget is clicked.
this._on( this.element, {
"click a": function( event ) {
event.preventDefault();
this.disable();
}
});
|
| enable() | jQuery (plugin only) | Enable the widget.
Code example: Enable the widget when any anchor of the widget is clicked.
this._on( this.element, {
"click a": function( event ) {
event.preventDefault();
this.enable();
}
});
|
| option( optionName ) | Object | Gets the value currently associated with the specifiedoptionNameassociated value.
Code example: Get the this.option( "width" ); |
| option() | PlainObject | Gets an object containing key/value pairs that represent the current widget options hash.
Code example: Log the key/value pairs of each widget option for debugging.
var options = this.option();
for ( var key in options ) {
console.log( key, options[ key ] );
}
|
| option( optionName, value ) | jQuery (plugin only) | Sets, with the specifiedoptionNamethe value of the associated widget option.
Code example: Set the this.option( "width", 500 ); |
| option( options ) | jQuery (plugin only) | Set one or more options for the widget.
Code example: Set the
this.option({
width: 500,
height: 500
});
|
| widget() | jQuery | Returns an object containing the original element or other related generated elementsjQueryobject.
Code example: When the widget is created, place a red border around the widget's original element.
_create: function() {
this.widget().css( "border", "2px solid red" );
}
|
| Events | Type | Description |
|---|---|---|
| create( event, ui ) | widgetcreate | Triggered when the widget is created.
Note: Code example: Initialize the widget with the specified create callback:
$( ".selector" ).widget({
create: function( event, ui ) {}
});
Bind an event listener to the widgetcreate event:
$( ".selector" ).on( "widgetcreate", function( event, ui ) {} );
|