Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery UI API - Widget Factory

jQuery UI API - Widget Factory

Category

Utilities | Widgets

jQuery.widget( name [, base ], prototype ) Usage

**Description:** Create stateful jQuery plugins using the same abstraction as all jQuery UI widgets.

jQuery.widget( name [, base ], prototype )

Parameters Type Type
name String The name of the widget to create, including the namespace.
base Function() The base widget to inherit from. It 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's prototype.

You can use the $.Widget Use an object as the base to inherit from, or explicitly create a new widget from scratch based on an existing jQuery UI or third-party widget. Defining a widget with the same name to inherit from a base widget even allows you to extend it appropriately.

jQuery UI contains many stateful widgets, so the usage pattern is slightly different from a typical jQuery plugin. 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 them all.

Note: This section uses the Progressbar Widget as an example, but the syntax applies to every widget.

Initialization

To track a widget's state, we must introduce the widget's full lifecycle. 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 every element in the jQuery object. In the example above, the element with id "elem"。

Option

Because progressbar() When called with no arguments, the widget is initialized with default options. We can pass a set of options at initialization to override the defaults:



$( "#elem" ).progressbar({ value: 20 });

We can pass as many options as needed; any option we do not pass uses its default value.

You can pass multiple option arguments, which are merged into a single object (similar to $.extend( true, target, object1, objectN )). This is useful for sharing options across instances while overriding some settings for all of them:



var options = { modal: true, show: "slow" };

$( "#dialog1" ).dialog( options );

$( "#dialog2" ).dialog( options, { autoOpen: false });

All options passed at initialization are deep-copied, ensuring that later changes to the object do not affect the widget. Arrays are the only exception; they are referenced as-is. This exception properly supports data binding, where the data source must be passed by reference.

Default values are stored on the widget's prototype, so we can override the values set by jQuery UI. For example, after the following, all future progressbar instances will default to a value of 80:



$.ui.progressbar.prototype.options.value = 80;

Options are part of a widget's state, so we can also set options after initialization. We will see the option method later.

Method

Now that the widget is initialized, we can query its state or perform actions on it. All post-initialization actions are performed as method calls. To call a method on a widget, we pass the method name to the jQuery plugin. For example, to call the value() method on a Progressbar Widget, we can use:



$( "#elem" ).progressbar( "value" );

If a method accepts arguments, we can pass them after the method name. For example, to pass the argument 40 to value() method on a Progressbar Widget, we can use:



$( "#elem" ).progressbar( "value", 40 );

As with 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 it provides. However, some methods exist on all widgets, which are explained in detail below.

Events

All widgets have events related to their various behaviors to notify you when state changes. For most widgets, when an event is fired, its name is prefixed with the lowercase name of the widget. For example, we can bind the Progressbar's change event, which fires 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 desired, we can hook into the Progressbar's change callback instead of binding an progressbarchange events.



$( "#elem" ).progressbar({

  change: function() {

    alert( "The value has changed!" );

  }

});

All widgets have a change event, which fires when the widget is instantiated.

Instantiation

A widget instance is stored in the element's data store under a key that is the widget's full name. jQuery.data() Therefore, you can use the following code to retrieve the Progressbar Widget instance object from an element.



$( "#elem" ).data( "ui-progressbar" );

To check whether an element is bound to a given widget, you can use the :data selector.



$( "#elem" ).is( ":data( 'ui-progressbar' )" ); // true

$( "#elem" ).is( ":data( 'ui-draggable' )" ); // false

You can also use :data to get a list of all elements that are instances of a given widget.



$( ":data( 'ui-progressbar' )" );

property

All widgets have the following properties:

jQuery.Widget Base Widget Usage

**Description:** The base widget used by the Widget Factory.

Quick navigation

Option Method Events

disabled

hide
show
|
_create
_delay
_destroy
_focusable
_getCreateEventData
_getCreateOptions
_hide
_hoverable
_init
_off
_on
_setOption
_setOptions
_show
_super
_superApply
_trigger
destroy
disable
enable
option
widget
|
create
|
Option Type Description Default value
disabled Boolean If set to true, the widget is disabled.
 

代码实例:

初始化带有指定 disabled 选项的小部件:


$( ".selector" ).widget({ disabled: true });     

After initialization, get or set disabled Option:

// getter

var disabled = $( ".selector" ).widget( "option", "disabled" );

// setter $( ".selector" ).widget( "option", "disabled", true );     

| false| onSelect | event | hide | Boolean or Number or String or Object | Whether to animate hiding the element, and how to animate hiding it.

Supports multiple types:

  • Boolean: when set to false when, no animation is used and the element is hidden immediately. When set to true when, the element fades out using the default duration and default easing.
  • Number: The element will fade out with the specified duration and default easing.
  • String: the element will be hidden using the specified effect. The value can be the name of a built-in jQuery animation method, such as "slideUp", or it can be a jQuery UI effect the name of, such as"fold". The effect in both cases will use the default duration and the default easing.
  • Object: if the value is an object, then effect、delay、duration and easing The property will be provided. If effect If the property contains the name of a jQuery method, use that method; otherwise, it is considered the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you can include these settings in the object and they will be passed on to the effect. If duration or easing If omitted, use the default value. If effect If omitted, use "fadeOut". If delay If omitted, no delay is used.

Code example:

Initializes with the specified hide The widget option:

$( ".selector" ).widget({ hide: { effect: "explode", duration: 1000 } });

    

After initialization, get or set hide Option:

// getter

var hide = $( ".selector" ).widget( "option", "hide" );

// setter $( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } );     

| null| onSelect | event | show | Boolean or Number or String or Object | Whether to animate showing the element, and how to animate showing it.

Supports multiple types:

  • Boolean: when set to false when, no animation is used and the element is shown immediately. When set to true when, the element fades in using the default duration and default easing.
  • Number: The element will fade in with the specified duration and default easing.
  • String: the element will be shown using the specified effect. The value can be the name of a built-in jQuery animation method, such as "slideDown", or it can be a jQuery UI effect of name, such as"fold". In both cases the effect will use the default duration and the default easing.
  • Object: if the value is an object, then effect、delay、duration and easing The property will be provided. If effect If the property contains the name of a jQuery method, use that method; otherwise, it is considered the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you can include these settings in the object and they will be passed on to the effect. If duration or easing If omitted, use the default value. If effect If omitted, use "fadeIn". If delay If omitted, no delay is used.

Code example:

Initializes with the specified show The widget option:

$( ".selector" ).widget({ show: { effect: "blind", duration: 800 } });

    

After initialization, get or set show Option:

// getter

var show = $( ".selector" ).widget( "option", "show" );

// setter $( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } );     

| null |

Method Return Description
_create() jQuery (plugin only) _create() The method is the constructor of the widget. It takes no arguments, but this.element and this.options has been set.
 
  • This method accepts no arguments.
  • Code example:

    Set the background color of the widget's element based on an option.

    _create: function() {
    
      this.element.css( "background-color", this.options.color );
    
    }
    
        
    | onSelect | event | _delay( fn [, delay ] ) | Number | Calls the provided function after the specified delay. Keeps the `this` context correct. Essentially `setTimeout()`. Returns the timeout ID for use with `clearTimeout()`.
    • fn
      Type: Function() or String
      Description: The function to call. It can also be the name of a method on the widget.
    • delay
      Type: Number
      Description: The number of milliseconds to wait before calling the function, defaults to 0。

    Code example:

    Called on the widget after 100 milliseconds _foo() method.

    this._delay( this._foo, 100 );
    
        
    | onSelect | event | _destroy() | jQuery (plugin only) | The public [`destroy()`](#method-destroy) method clears all public data, events, and so on. Represents the `_destroy()` for custom, widget-specific cleanup.
    • This method accepts no arguments.

    Code example:

    Removes a class from the widget's element when the widget is destroyed.

    _destroy: function() {
    
      this.element.removeClass( "my-widget" );
    
    }
    
        
    | onSelect | event | _focusable( element ) | jQuery (plugin only) | Sets up an `element` to apply the `ui-state-focus` class when focused.
    • element
      Type: jQuery
      Description: The element to which the focusable behavior is applied.

    Code example:

    Apply the focusable style to a set of elements within the widget:

    this._focusable( this.element.find( ".my-items" ) );
    
        
    | onSelect | event | _getCreateEventData() | Object | All widgets trigger the [`create`](#event-create) event. By default, no data is provided in the event, but this method can return an object that will be passed as data to the `create` event.
    • This method accepts no arguments.

    Code example:

    towards create The event handler passes the widget's options, as arguments.

    _getCreateEventData: function() {
    
      return this.options;
    
    }
    
        
    | onSelect | event | _getCreateOptions() | Object | This method allows the widget to define custom options during initialization. User-supplied options override the options returned by this method, and thus override the default options.
    • This method accepts no arguments.

    Code example:

    Make the id attribute of the widget's element available as an option.

    _getCreateOptions: function() {
    
      return { id: this.element.attr( "id" ) };
    
    }
    
        
    | onSelect | event | _hide( element, option [, callback ] ) | jQuery (plugin only) | Hide an element using a built-in animation method or a custom effect. For possible `option` values, see [hide](#option-hide).
    • element
      Type: jQuery
      Description: The element to hide.
    • option
      Type: Object
      Description: Settings that define how the element is hidden.
    • callback
      Type: Function()
      Description: The callback to invoke after the element is completely hidden.

    Code example:

    Pass for the custom animation hide option.

    this._hide( this.element, this.options.hide, function() {
    
    

    // Remove the element from the DOM when it's fully hidden. $( this ).remove(); });     

    | onSelect | event | _hoverable( element ) | jQuery (plugin only) | Establish events to apply when hovering over the element ui-state-hover class of element. Event handlers are automatically cleaned up on destroy.

    • element
      Type: jQuery
      Description: The element to which the hoverable behavior should be applied.

    Code example:

    When hovering over an element, to all of the div Apply the hoverable style.

    this._hoverable( this.element.find( "div" ) );
    
        
    | onSelect | event | _init() | jQuery (plugin only) | Widget initialization differs from creation. Any time the plugin is called with no arguments or with only an option hash, the widget is initialized. This method is included when the widget is created.

    Note: If there is logic to execute when the widget is successfully called with no arguments, initialization is the only place to handle it.

    • This method accepts no arguments.

    Code example:

    If set autoOpen option, then call open() method.

    _init: function() {
    
      if ( this.options.autoOpen ) {
    
        this.open();
    
      }
    
    }
    
        
    | onSelect | event | _off( element, eventName ) | jQuery (plugin only) | Unbinds event handlers from the specified element.
    • element
      Type: jQuery
      Description: The element from which to unbind the event handler. Unlike _on() method,_off() The element is required in the method.
    • eventName
      Type: String
      Description: One or more space-separated event types.

    Code example:

    Unbind all click events from the widget's element.

    this._off( this.element, "click" );
    
        
    | onSelect | event | _on( [suppressDisabledCheck ] [, element ], handlers ) | jQuery (plugin only) | Delegation via selectors within the event name is supported, for example `"click .foo"`. The `_on()` method provides several benefits of direct event binding:
    • Keep it appropriate inside of the handler. this context.
    • Automatically handle disabled widgets: if a widget is disabled or an event occurs on an element with a ui-state-disabled class of elements, the event handler is not called. It can be suppressDisabledCheck The parameter is overridden.
    • Event handlers are automatically namespaced and cleaned up on destroy.
    • suppressDisabledCheck(default value:false)
      Type: Boolean
      Description: Whether to bypass the disabled check.
    • element
      Type: jQuery
      Description: The element to which to bind the event handler. If no element is provided,this.element Used for unauthorized events,widget element for delegated events.
    • handlers
      Type: Object
      Description: A map where string keys represent event types, an optional selector is used for delegation, and values represent the handlers invoked for the event.

    Code example:

    Prevent the default behavior of all clicked links within the widget's element.

    this._on( this.element, {
    
      "click a": function( event ) {
    
        event.preventDefault();
    
      }
    
    });
    
        
    | onSelect | event | _setOption( key, value ) | jQuery (plugin only) | Called for each individual option by the _setOptions() method. The widget state is updated with the change.
    • key
      Type: String
      Description: The name of the option to set.
    • value
      Type: Object
      Description: The value to set for the option.

    Code example:

    When the widget's height or width When the option changes, update the widget's element.

    _setOption: function( key, value ) {
    
      if ( key === "width" ) {
    
        this.element.width( value );
    
      }
    
      if ( key === "height" ) {
    
        this.element.height( value );
    
      }
    
      this._super( key, value );
    
    }
    
        
    | onSelect | event | _setOptions( options ) | jQuery (plugin only) | Called when the [`option()`](#method-option) method is called, regardless of the form in which `option()` is called. Overriding this method is useful if you need to change handling when multiple options are changed at once.
    • options
      Type: Object
      Description: The value to set for the option.

    Code example:

    If the widget's height or width When the option changes, call resize method.

    _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(); } }     

    | onSelect | event | _show( element, option [, callback ] ) | jQuery (plugin only) | Display an element using the built-in animation methods or a custom effect. For possible option value, please see show。

    • element
      Type: jQuery
      Description: The element to show.
    • option
      Type: Object
      Description: Settings that define how the element is shown.
    • callback
      Type: Function()
      Description: The callback to invoke after the element is completely shown.

    Code example:

    Pass for the custom animation show option.

    this._show( this.element, this.options.show, function() {
    
    

    // Focus the element when it's fully visible. this.focus(); }     

    | onSelect | event | _super( [arg ] [, ... ] ) | jQuery (plugin only) | Calls the method of the same name from the parent widget, with any specified arguments. Essentially .call()。

    • arg
      Type: Object
      Description: Zero or more arguments to pass to the parent widget's method.

    Code example:

    Handling title The option is updated, and calls the parent widget's _setOption() to update the option's internal storage.

    _setOption: function( key, value ) {
    
      if ( key === "title" ) {
    
        this.element.find( "h3" ).text( value );
    
      }
    
      this._super( key, value );
    
    }
    
        
    | onSelect | event | _superApply( arguments ) | jQuery (plugin only) | Calls the method of the same name from the parent widget with an array of arguments. Essentially `.apply()`.
    • arguments
      Type: Array
      Description: An array of arguments to pass to the parent widget's method.

    Code example:

    Handling title The option is updated, and calls the parent widget's _setOption() to update the internal storage of the option.

    _setOption: function( key, value ) {
    
      if ( key === "title" ) {
    
        this.element.find( "h3" ).text( value );
    
      }
    
      this._superApply( arguments );
    
    }
    
        
    | onSelect | event | _trigger( type [, event ] [, data ] ) | Boolean | Triggers an event and its associated callbacks. An option with the same name as the type is invoked as a callback.

    The event name is the widget name and the type in lowercase letters joined together.

    Note: When providing data, you must provide all three arguments. If no event is passed, then pass null。

    If the default behavior is prevented, return false; otherwise, returns true. When the handler returns false when, or when calling event.preventDefault() when, the default behavior is prevented.

    • type
      Type: String
      Description:type should match the name of the callback option. The complete event type is generated automatically.
    • event
      Type: Event
      Description: The original event that caused this event, useful for providing context to listeners.
    • data
      Type: Object
      Description: A hash of data related to the event.

    Code example:

    When a key is pressed, trigger search events.

    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()
    
    });
    
    

    } });     

    | onSelect | event | destroy() | jQuery (plugin only) | Completely removes the widget functionality. This returns the element to its pre-initialization state.

    • This method accepts no arguments.

    Code example:

    Destroys the widget when any anchor point of the widget is clicked.

    this._on( this.element, {
    
      "click a": function( event ) {
    
        event.preventDefault();
    
        this.destroy();
    
      }
    
    });
    
        
    | onSelect | event | disable() | jQuery (plugin only) | Disables the widget.
    • This method accepts no arguments.

    Code example:

    Disables the widget when any anchor of the widget is clicked.

    this._on( this.element, {
    
      "click a": function( event ) {
    
        event.preventDefault();
    
        this.disable();
    
      }
    
    });
    
        
    | onSelect | event | enable() | jQuery (plugin only) | Enables the widget.
    • This method accepts no arguments.

    Code example:

    Enables the widget when any anchor of the widget is clicked.

    this._on( this.element, {
    
      "click a": function( event ) {
    
        event.preventDefault();
    
        this.enable();
    
      }
    
    });
    
        
    | onSelect | event | option( optionName ) | Object | Get the value currently associated with the specified `optionName`.
    • optionName
      Type: String
      Description: The name of the option to get.

    Code example:

    Get width Options of values.

    this.option( "width" );
    
        
    | onSelect | event | option() | PlainObject | Gets an object containing key/value pairs, where the pairs represent the current widget options hash.
    • This method accepts no arguments.

    Code example:

    Logs the key/value pair of each widget option for debugging.

    var options = this.option();
    
    for ( var key in options ) {
    
      console.log( key, options[ key ] );
    
    }
    
        
    | onSelect | event | option( optionName, value ) | jQuery (plugin only) | Sets the value of the widget option associated with the specified `optionName`.
    • optionName
      Type: String
      Description: The name of the option to set.
    • value
      Type: Object
      Description: The value to set for the option.

    Code example:

    Settings width The options are 500。

    this.option( "width", 500 );
    
        
    | onSelect | event | option( options ) | jQuery (plugin only) | Sets one or more options for the widget.
    • options
      Type: Object
      Description: The option-value pairs to set.

    Code example:

    Settings height and width The options are 500。

    this.option({
    
      width: 500,
    
      height: 500
    
    });
    
        
    | onSelect | event | widget() | jQuery | Returns a `jQuery` object containing the original element or other related generated elements.
    • This method accepts no arguments.

    Code example:

    When the widget is created, places 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.
     
  • event
    Type: Event
  • ui
    Type: Object
  • Note:ui The object is empty; it is included here for consistency with other events.

    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 ) {} );
    
        
    |